如何验证输入以使其必须是整数

时间:2013-08-14 09:02:17

标签: validation python-3.x integer

我正在尝试验证输入,以便它必须是整数。我已经验证了输入,使其必须在一定范围内,但如果输入字母'b',则会出现错误,显示为“ValueError:intl(对于基数为10的intl无效”)。如果值不是整数,我希望在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-->  "))

1 个答案:

答案 0 :(得分: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')