很抱歉,如果问题已解决,但这是一些简单的代码。
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
并显示为该字符串设置的内容,即{{1 }}
有没有办法实现这个目标?
答案 0 :(得分: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
。