0

我目前有这个代码:

yon = raw_input("were you running in km y or n?: ")
if yon is "y":
    kilnumber = raw_input("how many kilometers?: ")
    milnumber = 0
    try:
        float(kilnumber)
    except:
        print "You must enter a number"
        exit()

如果用户输入非法响应,我希望通过添加一个 while 循环来重新询问 kilnumber 来使其更简单。我希望有这样的事情:

yon = raw_input("were you running in km y or n?: ")
if yon is 'y':
    kilnumber = raw_input("how many kilometers?: ")
    milnumber = 0
    while float(kilnumber) is ValueError:
        print "You must enter a number"
        kilnumber = raw_input("how many kilometers?: ")

此代码不起作用,因为它在评估 while 循环之前发送错误消息。解决方案?

4

2 回答 2

5

float(kilnumber)永远不会评估为ValueError. 相反,它可能会抛出一个ValueError. 你需要抓住它:

while True:
    try:
        float(kilnumber)
    except ValueError:
        # Not a valid number
        print "You must enter a number"
        kilnumber = raw_input("how many kilometers?: ")
    else:
        # No error; stop the loop
        break

有关异常和错误的更多信息,请参阅教程

于 2013-11-13T07:56:05.290 回答
0

你认为这是什么意思?

while float(kilnumber) is ValueError:

float(kilnumber)永远不会是 a ValueError,它可以抛出一个。所以你必须使用try/catch. 您可以将其放入一个while循环中,以检查指示输入了正确数据的变量。

于 2013-11-13T07:55:03.760 回答