检查输入是否为 1 到 3 之间的整数 - Python
Checking that input is an integer between 1 and 3 - Python
我希望能够检查输入是否为 1 到 3 之间的整数,目前我有以下代码:
userChoice = 0
while userChoice < 1 or userChoice > 3:
userChoice = int(input("Please choose a number between 1 and 3 > "))
这会让用户重新输入一个不在 1 和 3 之间的数字,但我想添加验证以确保用户无法输入可能导致值错误的字符串或不寻常的字符。
赶上 ValueError
:
Raised when a built-in operation or function receives an argument that
has the right type but an inappropriate value
示例:
while userChoice < 1 or userChoice > 3:
try:
userChoice = int(input("Please choose a number between 1 and 3 > "))
except ValueError:
print('We expect you to enter a valid integer')
其实,由于允许的数字范围较小,可以直接对字符串进行操作:
while True:
num = input('Please choose a number between 1 and 3 > ')
if num not in {'1', '2', '3'}:
print('We expect you to enter a valid integer')
else:
num = int(num)
break
或者尝试比较所需结果中的 input
和循环中的 break
,如下所示:
while True:
# python 3 use input
userChoice = raw_input("Please choose a number between 1 and 3 > ")
if userChoice in ('1', '2', '3'):
break
userChoice = int(userChoice)
print userChoice
使用Try/Except
是一个很好的方法,但是你原来的设计有一个缺陷,因为用户仍然可以输入像“1.8”这样的输入,它不是一个整数,但会通过你的检查。
我希望能够检查输入是否为 1 到 3 之间的整数,目前我有以下代码:
userChoice = 0
while userChoice < 1 or userChoice > 3:
userChoice = int(input("Please choose a number between 1 and 3 > "))
这会让用户重新输入一个不在 1 和 3 之间的数字,但我想添加验证以确保用户无法输入可能导致值错误的字符串或不寻常的字符。
赶上 ValueError
:
Raised when a built-in operation or function receives an argument that has the right type but an inappropriate value
示例:
while userChoice < 1 or userChoice > 3:
try:
userChoice = int(input("Please choose a number between 1 and 3 > "))
except ValueError:
print('We expect you to enter a valid integer')
其实,由于允许的数字范围较小,可以直接对字符串进行操作:
while True:
num = input('Please choose a number between 1 and 3 > ')
if num not in {'1', '2', '3'}:
print('We expect you to enter a valid integer')
else:
num = int(num)
break
或者尝试比较所需结果中的 input
和循环中的 break
,如下所示:
while True:
# python 3 use input
userChoice = raw_input("Please choose a number between 1 and 3 > ")
if userChoice in ('1', '2', '3'):
break
userChoice = int(userChoice)
print userChoice
使用Try/Except
是一个很好的方法,但是你原来的设计有一个缺陷,因为用户仍然可以输入像“1.8”这样的输入,它不是一个整数,但会通过你的检查。