4

所以我在这里要做的是,如果你输入一个字符串而不是一个整数,你就会回到开头

但是由于某种原因,当你输入一个字符串时程序就会停止

while True:
    try:
        print("Will select a random number between selected limits: 'x' and 'y'")
        x = int(input("x = "))
    except ValueError:
        print("Please enter a number")
        break
4

2 回答 2

5
while True:
    try:
        print("Will select a random number between selected limits: 'x' and 'y'")
        x = int(input("x = "))
        y = int(input("y = "))
    except ValueError:
        print("Please enter a number") # don't break here, let loop repeat
    else:
        break # only break when there is no error
于 2013-05-22T13:43:58.640 回答
1

更短,一行;):

while True:
    try:
        print("Will select a random number between selected limits: 'x' and 'y'")
        x = int(input("x = "))
        y = int(input("y = "))
        break # only break when there is no error
    except ValueError:
        print("Please enter a number") # don't break here, let loop repeat
于 2013-05-22T13:54:19.327 回答