我需要限制允许的无效输入的数量,以便在给定的尝试次数后程序退出。
输入小于零定义为无效。
假设尝试次数为 3。
def number():
number = float(input('please enter a number (must be greater thatn zero): '))
if number >= 0 :
print ('you choose number:', number)
else:
print ('invalid input')
return
number()
我如何限制无效输入尝试的次数并使代码能够返回再次询问问题并提示输入但仍然跟踪以前的尝试?
最佳答案
您必须使用循环,在这种情况下,while
循环会很方便。您必须声明一个变量 invalid_attempts
来记录用户提供的无效输入的次数。
完成循环的条件是当 invalid_attempts
大于或等于 3
时,它会在您获得无效输入时增加。您可能需要更改 3
以满足您的要求:
def get_input():
invalid_attempts = 0
while invalid_attempts < 3:
number = float(input('please enter a number (must be greater thatn zero): '))
if number >= 0 :
print ('you choose number:', number)
return number # so you can call the method as 'some_variable = get_input()'
else:
print ('invalid input')
invalid_attempts += 1
注意:因为 number
是方法的名称,所以你不应该在内部调用一个同名的变量(因为如果你这样做,你就不会能够在内部使用该函数,如果有必要的话),在这种情况下,我正在调用方法 get_input
。
关于python - 限制 python 3 中的无效输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22274766/