0

我正在尝试验证输入,以便它必须是整数。我已经验证了输入,因此它必须在一定范围内,但是如果他们输入字母“b”,例如,就会出现错误,显示为“ValueError:invalid literl for int() with base 10”。如果值不是整数,我希望在 else 部分中显示相同的消息。我已经在网上搜索了一段时间,无法弄清楚如何验证输入,所以它必须是一个整数。

Minutes=int(input("How long do you want the interval between each stretch to be?\nIndicate a number in minutes between 5 and 60\n\nAfter the minutes specified, a window with suggested stretches will appear\n--> "))

y=1 而 y==1:

if Minutes in range (4,61):
    TimeMinute (Minutes) #(Minutes needs to be multiplied by 60 to make it into minutes) Minutes is currently in the unit of seconds
    y=0
else:
    Minutes=int(input ("Error. You need to enter a number between 5 and 60.\nHow long do you want the interval between each stretch to be?\nIndicate a number in minutes between 5 and 60\nAfter the minutes specified, a window with suggested stretches will appear\n-->  "))
4

1 回答 1

0

您应该首先获取用户输入,然后尝试将其解析为整数,如果失败(引发ValueError)然后打印错误消息,如果它是有效整数,则检查范围并执行您想要的任何操作。

value = input('Enter minutes :')
try:
    value = int(value)
    if 4 < value < 61:
       # Do your stuff
    else:
       print('Error value must be in range: 5-60')
except ValueError:
   print('The value you entered is not a valid integer value')
于 2013-08-14T10:00:29.640 回答