python尝试除格式

时间:2012-12-04 00:32:39

标签: python

try:
    num = int(input("Give me an integer between 1 and 100:"))
    while num > 100 or num < 1:
        print ("Sorry, that is not an integer between 1 and 100. Try again.")
        num = int(input("Give me an integer between 1 and 100:"))
except:
    print ("Sorry, that is not an integer between 1 and 100. Try again.")
else:
    print ("Thank you for your input")

如果他们输入“pear”或“sd23214”这样的输入,我如何告诉Python还打印“抱歉再试一次”?谢谢。

2 个答案:

答案 0 :(得分:3)

将其全部包装在while循环

while True:
    try:
        num = int(input("Give me an integer between 1 and 100:"))
        if num > 100 or num < 1:
            print ("Sorry, that is not an integer between 1 and 100. Try again.")
            continue
    except ValueError:
        print ("Sorry, that is not an integer between 1 and 100. Try again.")
    else:
        print ("Thank you for your input")
        break

大多数人可能不会在这里使用else子句

while True:
    try:
        num = int(input("Give me an integer between 1 and 100:"))
        if num > 100 or num < 1:
            raise ValueError
        print ("Thank you for your input")
        break
    except ValueError:
        print ("Sorry, that is not an integer between 1 and 100. Try again.")

答案 1 :(得分:1)

这是一种更好/更简单的方法(在我看来):

while True:
    try:
        num = int(input("Enter an integer between 1 and 100: "))
        if type(num) != int or num not in range(1, 101): #second argument is exclusive
            raise ValueError
        else:
            print("Thank you.")
            break
    except ValueError:
        print("Input must be an integer within 1 and 100. Try again.")

使用range是一种很好的方法,而不是使用if num > 101 or num < 1