在Python中如何忽略'for'语句中的无效输入?

0 投票
2 回答
617 浏览
提问于 2025-04-18 08:17

我正在尝试写一个程序,让它循环提示用户输入10次,或者直到用户输入正确的内容为止。如果用户输入错误的内容,这次输入就不算在10次尝试之内。我不太确定应该把提示放在for循环里面还是外面。关于错误输入的问题,我现在有的代码是这样的:

for i in range(10):
    value=input("Enter a numerical value: ")
    if value.isdigit()==False:
       print("Error.")

2 个回答

0

当你得到正确的输入时,你需要结束这个循环

for i in range(10):
    value=input("Enter a numerical value: ")
    if not value.isdigit():  # PEP8 says to use `not` instead of `== False`
        print("Error.")
    else:
        break  # If we get here, the input was good.  So, break the loop.

下面是一个演示:

>>> for i in range(10):
...     value=input("Enter a numerical value: ")
...     if not value.isdigit():
...         print("Error.")
...     else:
...         break
...
Enter a numerical value: a
Error.
Enter a numerical value: b
Error.
Enter a numerical value: 12
>>>
3

更好的做法是使用while循环。

与其固定循环10次,不如循环直到你获得一个有效的输入,也就是说:

while True:
    value = input("Enter a number:")
    if value.isdigit() == False:
        print "Error"
    else: 
        break

不过,如果你只想最多循环10次,你现在的做法也是可以的——你只需要一种方法来在输入有效数字时退出循环。

for i in range(10):
    value=input("Enter a numerical value: ")
    if value.isdigit()==False:
        print("Error.")
    else:#is a digit
        break

看到你的评论后,我还是建议使用while循环,只是需要加一个额外的变量(并根据DarinDouglass的评论做一些修改)。

times_correct = 0
while times_corrent < 10:
    value = input("Enter a number:")
    if value.isdigit() == False:
        print "Error"
    else:
        times_corrent += 1

撰写回答