我正在尝试进行多项选择调查,允许用户从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!')
Run Code Online (Sandbox Code Playgroud)
您的代码将变为:
def Survey():
print('1) Blue')
print('2) Red')
print('3) Yellow')
while True:
try:
question = int(input('Out of these options\(1,2,3), which is your favourite?'))
break
except:
print("That's not a valid option!")
if question == 1:
print('Nice!')
elif question == 2:
print('Cool')
elif question == 3:
print('Awesome!')
else:
print('That\'s not an option!')
Run Code Online (Sandbox Code Playgroud)
它的工作方式是它创建一个无限循环的循环,直到只输入数字.所以说我放'1',它会打破循环.但是,如果我把'Fooey!' WOULD引发的错误被except
语句捕获,并且因为它没有被破坏而循环.
最好的方法是使用一个辅助函数,它可以接受一个变量类型以及接收输入的消息。
def _input(message, input_type=str):
while True:
try:
return input_type (input(message))
except:pass
if __name__ == '__main__':
_input("Only accepting integer : ", int)
_input("Only accepting float : ", float)
_input("Accepting anything as string : ")
Run Code Online (Sandbox Code Playgroud)
所以当你想要一个整数时,你可以传递它我只想要整数,以防万一你可以接受浮点数,你将浮点数作为参数传递。它会让你的代码变得非常苗条,所以如果你必须输入 10 次,你不想写十次 try catch 块。
归档时间: |
|
查看次数: |
40027 次 |
最近记录: |