无法在 if-loop 中使用 str 在 Python 3 中工作

2024-09-29 03:24:13 发布

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

我写了一个分数计算器,你在里面放一个浮点数,然后根据你的得分得到一个分数。我的问题是,我相信我需要一个浮动(输入。。。但是如果你在盒子里写信,那就成了一个错误。。。你知道吗

def scoreGrade():
"""
Determine the grade from a score
"""
gradeA = "A"
gradeB = "B"
gradeC = "C"
gradeD = "D"
gradeF = "F"

score = float(input("Please write the score you got on the test, 0-10: "))
if score >= 9:
    print("You did really good, your grade is:", gradeA, ". Congratulations")
elif score >= 7:
    print("Your results are good. They earn you a:", gradeB, ". Better luck next time")
elif score >= 5:
    print("Not too bad. You got a:", gradeC)
elif score >= 4:
    print("That was close...:", gradeD)
elif score < 4:
    print("You need to step up and take the test again:", gradeF)
else:
    print("Grow up and write your score between 0 and 10")

如果你写了一些分数在0-10之间的东西,有没有办法去掉浮点数并打印最后一个语句?你知道吗


Tags: andtheyou分数writegradescoreprint
3条回答

像这样:

score = None
while score is None:
    try:
        score = float(input("Please write the score you got on the test, 0-10: "))
    except ValueError:
        continue

继续询问,直到float转换工作,而不引发ValueError异常。你知道吗

你能做到的

try:
    score = float(input("Please write the score you got on the test, 0-10: "))
except ValueError:
    print("Grow up and write your score between 0 and 10")
    scoreGrade()

我建议使用EAFP方法,分别处理好的和坏的输入。你知道吗

score_as_string = input("Please write the score you got on the test, 0-10: ")
try:
    score_as_number = float(score_as_string)
except ValueError:
    # handle error
else:
    print_grade(score_as_number)

def print_grade(score):
"""
Determine the grade from a score
"""
gradeA = "A"
gradeB = "B"
gradeC = "C"
gradeD = "D"
gradeF = "F"

if score >= 9:
    print("You did really good, your grade is:", gradeA, ". Congratulations")
elif score >= 7:
    print("Your results are good. They earn you a:", gradeB, ". Better luck next time")
elif score >= 5:
    print("Not too bad. You got a:", gradeC)
elif score >= 4:
    print("That was close...:", gradeD)
elif score < 4:
    print("You need to step up and take the test again:", gradeF)
else:
    print("Grow up and write your score between 0 and 10")

请注意,通常您希望从函数返回,而不是在函数中打印。使用函数输出作为print语句的一部分非常详细,函数不必知道这一点。你知道吗

相关问题 更多 >