2017-04-17 54 views
2

對不起,如果問題關閉,但這是一些簡單的代碼。加入變量和字符串以獲得變量

quiz_description = 'A quiz to test your knowledge' 
quiz_type = 'This quiz is about social studies' 
quiz_length = 'This test is five minutes long' 

while 0 == 0: 
    user_input = input('What do you want to know about the quiz? (length|type|description)\n') 

    print('quiz_' + user_input) 

此代碼將導致

quiz_lenght

但我想加盟quiz_user_input,這是length,並導致quiz_lenght和顯示的內容設置該字符串,這是'This test is five minutes long'

有沒有辦法達到這個目的?

回答

4

你應該實現這個使用字典:

quiz = { 
    'description': 'A quiz to test your knowledge', 
    'type': 'This quiz is about social studies', 
    'length': 'This test is five minutes long', 
} 

while 0 == 0: 
    user_input = input('What do you want to know about the quiz? (length|type|description)\n') 

    print(quiz.get(user_input, 'Please choose a correct attribute!') 

dict.get將嘗試找到基於第一個參數一個鍵的值。如果它沒有找到該鍵(即,如果用戶沒有輸入其中一個建議值),它將返回第二個參數中的值。這將阻止獲得KeyError