我正在尝试进行多项选择调查,允许用户从选项 1-x 中进行选择。我怎样才能做到这一点,如果用户输入数字以外的任何字符,则返回类似“这是无效答案”的内容
def Survey():
print('1) Blue')
print('2) Red')
print('3) Yellow')
question = int(input('Out of these options\(1,2,3), which is your favourite?'))
if question == 1:
print('Nice!')
elif question == 2:
print('Cool')
elif question == 3:
print('Awesome!')
else:
print('That\'s not an option!')
原文由 user3578683 发布,翻译遵循 CC BY-SA 4.0 许可协议
您的代码将变为:
它的工作方式是创建一个无限循环,直到只输入数字。所以说我输入“1”,它会打破循环。但如果我放“Fooey!”本应引发的错误被
except
语句捕获,并且它循环,因为它没有被破坏。