我目前有这个代码:
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 循环之前发送错误消息。解决方案?