
[英]How can I limit the user input to only certain integers (ie: Only between 1-100, which also includes 1 and 100) in Python
[英]How can I limit the user input to only integers in Python
我正在尝试进行多项选择调查,允许用户从选项 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!')
你的代码会变成:
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!')
它的工作方式是创建一个循环,该循环将无限循环,直到只输入数字。所以说我输入“1”,它会破坏循环。 但是如果我输入“Fooey!” 将引发的错误被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 : ")
所以当你想要一个整数时,你可以传递它,我只想要整数,以防万一你可以接受浮点数,你将浮点数作为参数传递。 它会让你的代码变得非常苗条,所以如果你必须输入 10 次,你不想写十次 try catch 块。
def func():
choice = "Wrong"
while choice.isdigit()==False :
choice = input("Enter a number: ")
if choice.isdigit()==False:
print("Wrongly entered: ")
else:
return int(choice)
除其他解决方法一:使用type
函数或isinstance
函数来检查,如果你有一个int
或float
或一些其他类型
>>> type(1)
<type 'int'>
>>> type(1.5)
<type 'float'>
>>> isinstance(1.5, int)
False
>>> isinstance(1.5, (int, float))
True
我会首先捕获ValueError
(不是整数)异常并检查答案是否可以接受(在 1、2、3 内)或引发另一个ValueError
异常
def survey():
print('1) Blue')
print('2) Red')
print('3) Yellow')
ans = 0
while not ans:
try:
ans = int(input('Out of these options\(1, 2, 3), which is your favourite?'))
if ans not in (1, 2, 3):
raise ValueError
except ValueError:
ans = 0
print("That's not an option!")
if ans == 1:
print('Nice!')
elif ans == 2:
print('Cool')
elif ans == 3:
print('Awesome!')
return None
您可以使用名为 PyInputPlus 的模块
pip 安装 PyInputPlus
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!')# answered after 7 years
我为这种情况制作了一个模块,称为restricted_input ,它实时检查输入。 在这里,由于您只需要 1-3 的输入,因此可以
from restricted_input import r_input
num = int(r_input("Out of these options\(1,2,3), which is your favourite? ", input_type="nothing", allow="123", maxlength=1))
它使用 msvcrt.getch/termios 来获取非阻塞输入,因此它会实时检查它并且只允许指定的字符。
注意:这不适用于 Spyder、Jupyter 等 IDLE。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.