else语句上的函数问题错误

2024-06-02 17:19:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在研究Charles Severance的《为每个人编写Python》一书。我被其中的一个问题困住了,即使是一个在线工作的例子似乎也不能完全回答这个问题

Exercise 7: Rewrite the grade program from the previous chapter using a function called computegrade that takes a score as its parameter and returns a grade as a string.


Score

>= 0.9 A
>= 0.8 B
>= 0.7 C
>= 0.6 D
<0.6 F



Enter score: 0.95

A

Enter score: perfect

Bad score

Enter score: 10.0

Bad score

Enter score: 0.75

C

Enter score: 0.5

F

Run the program repeatedly to test the various different values for input.

我的代码是:

def computegrade(score):
    if float(score)>1:
        return 'Bad score'
    elif float(score)>=0.9:
        return 'A'
    elif float(score)>=0.8:
        return 'B'
    elif float(score)>=0.7:
        return 'C'
    elif float(score)>=0.6:
        return 'D'
    elif float(score)<0.6:
        return 'F'
    else:
        return 'Bad score'

…在我输入“完美”或任何类型的非数字输入(抛出错误)之前,这似乎都是有效的。我只是想知道,当word输入不符合其他条件时,为什么我的else语句不能使用这种方法


Tags: thereturnasfloatprogramelse例子grade
2条回答
def computegrade(score):
    try:
        score = float(score)
    except ValueError:
        return 'Bad Score'
            
    if score > 1:
        return 'Bad score'
    elif score >= 0.9:
        return 'A'
    elif score >= 0.8:
        return 'B'
    elif score >= 0.7:
        return 'C'
    elif score >= 0.6:
        return 'D'
    elif score < 0.6:
        return 'F'

a = computegrade(input())
print(a)

与大多数编程语言一样,python中的if..elif...else是按顺序工作的,这意味着从函数中执行if float(score)>1:行。现在,一旦您看到完整的错误,您将看到python已经将您指向这一行作为错误。 在这一行中,它试图将任何非数字输入转换为浮点数,但它不能。这就是你的错误

如果要解决这些问题,必须使用异常处理。也就是说,当您没有获得所需的数据类型时,您希望避免程序崩溃。正如这里所解释的-{a1},以及一些其他答案所建议的那样,try...catch非常有用。此外,还有许多其他方法,如switch casetype checking

注意:

  • 考虑到OP,我正在为我解释的一些方法添加链接,这可能对其他方法也有帮助
  • 类型检查可能不是一个好主意,但是可以用类型检查if score.isnumeric()解决这个问题,但这只适用于整数值,而不适用于浮点值

相关问题 更多 >