【发布时间】:2015-06-24 22:27:09
【问题描述】:
我有一个简单的 python(2.7.3 版)代码,它的输出我无法弄清楚。代码提示用户输入分数(如果输入不是从 0 到 1 的数字,将继续这样做),确定字母等级,然后退出。代码如下:
def calc_grade():
try:
score = float(raw_input("Enter a score: "))
if score > 1.0:
print "Error: Score cannot be greater than 1."
calc_grade()
except:
print "Error: Score must be a numeric value from 0 to 1."
calc_grade()
print "\nthe score is: %s" % (score)
if score >= 0.9:
print "A"
elif score >= 0.8:
print "B"
elif score >= 0.7:
print "C"
elif score >= 0.6:
print "D"
else:
print "F"
return 0
calc_grade()
如果我运行这个脚本并尝试输入:1.5、h、0.8,那么我会得到以下输出:
Enter a score: 1.5
Error: Score cannot be greater than 1.
Enter a score: h
Error: Score must be a numeric value from 0 to 1.
Enter a score: 0.8
the score is: 0.8
B
Error: Score must be a numeric value from 0 to 1.
Enter a score: 0.7
the score is: 0.7
C
the score is: 1.5
A
如您所见,在输入有效值 (0.8) 后,脚本会打印出正确的等级 (B),但脚本并没有像我预期的那样结束。相反,它会打印出非数字值的错误消息,然后提示用户再次输入分数。如果我输入另一个有效分数(在本例中为 0.7),则脚本会打印出正确的成绩 (C),然后打印出第一个错误的输入 (1.5) 及其成绩 (A)。
在我的一生中,我无法弄清楚是什么导致了这种“功能”。有什么建议吗?
【问题讨论】:
-
您的异常处理程序正在捕获
UnboundLocalError以及您所期望的ValueError。
标签: python