0
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")

How do I tell Python to also print "sorry try again" if they entered input such as "pear" or "sd23214"? Thank you.

4

2 回答 2

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.")
于 2012-12-04T00:37:40.183 回答
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.")

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

于 2012-12-04T00:47:06.837 回答