简单的Python代码出错

Sha*_*aun 3 python

我有一个简单的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()
Run Code Online (Sandbox Code Playgroud)

如果我运行此脚本,请尝试输入: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
Run Code Online (Sandbox Code Playgroud)

如您所见,在输入有效值(0.8)后,脚本会输出正确的等级(B),但脚本不会像我预期的那样结束.相反,它会打印出非数字值的错误消息,然后提示用户再次输入分数.如果我输入另一个有效分数(在这种情况下为0.7),则脚本打印出正确的等级(C),然后打印出第一个错误输入(1.5)及其等级(A).

在我的生活中,我不能弄清楚是什么导致了这个"功能".有什么建议?

Mur*_*nik 7

在发生任何错误时,您calc_grade再次以递归方式调用,因此如果输入的输入无效,则需要多次调用.相反,您应该迭代地处理错误的错误:

def calc_grade():
    score = None
    while score is None:     
        try:
            score = float(raw_input("Enter a score: "))
            if score > 1.0:
                print "Error: Score cannot be greater than 1."
                score = None
        except:
            print "Error: Score must be a numeric value from 0 to 1."

    # If we reached here, score is valid,
    # continue with the rest of the code
Run Code Online (Sandbox Code Playgroud)