检查用户输入以查看它是否满足两个条件

时间:2016-07-14 17:27:41

标签: python python-3.x try-except

作为更大的菜单驱动程序的一部分,我想测试用户输入以查看是否输入: 是一个整数 AND 如果是整数,如果它在1到12的范围内,包括

number = 0    
while True:
    try:
            number = int(input("Enter a whole number between 1 and 12 >>> "))
    except ValueError:
            print("Invlaid input, please try again >>> ")
            continue
    else:   
            if not (1<= number <=12):
                    print("Need a whole number in range 1-12 >>> ")
                    continue
            else:   
                    print("You selected:",number)
                    break

我正在使用Python 3.4.3,并想知道是否有更简洁(更少的行,更好的性能,更多的“Pythonic”,例如)方法来实现这一目标?提前致谢。

4 个答案:

答案 0 :(得分:1)

如果中的,那么你不需要一个

while True:
    try:
        number = int(input("Enter a whole number between 1 and 12 >>> "))
        if 1 <= number <= 12:
            print("You selected:", number)
            break
        print("Need a whole number in range 1-12 >>> ")
    except ValueError:
            print("Invlaid input, please try again >>> ")

错误的输入意味着你直接去除了,如果输入是好的并且在你接受的范围内,print("You selected:", number)并且将被执行然后我们中断或者否则print("Need a whole number in range 1-12 >>> ")将被执行超出范围。

答案 1 :(得分:0)

您的代码对我来说非常好。小修正(拼写,缩进,不必要的continue):

while True:
    try:
        number = int(input("Enter a whole number between 1 and 12 >>> "))
    except ValueError:
        print("Invalid input, please try again >>> ")
    else:   
        if 1 <= number <= 12:
            print("You selected: {}".format(number))
            break
        else:
            print("Need a whole number in range 1-12 >>> ")

答案 2 :(得分:0)

使用isdigit()检查非数字字符。那你就不应该抓住异常了。只有一个if并且如果blah包含非数字,它会使用运算符短路来避免执行int(blah)。

while True:
    num_str = raw_input("Enter a whole number between 1 and 12 >>> ")
    if num_str.isdigit() and int(num_str) in range(1,13):
        print("You selected:",int(num_str))
        break
    else:
        print("Need a whole number in range 1-12 >>> ")

答案 3 :(得分:-1)

我认为您不需要整个try / except阻止。一切都可以融入一个条件:

number = raw_input("Enter a whole number between 1 and 12 >>> ")
while not (number.isdigit() and type(eval(number)) == int and 1<= eval(number) <=12):
    number = raw_input("Enter a whole number between 1 and 12 >>> ")
print("You selected:",number)