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

时间:2015-03-02 18:43:41

标签: python string python-3.x

我写了一个成绩计算器,你可以在其中放入一个浮点数并根据你的得分得到一个等级。我遇到的问题是我相信我需要一个浮点数(输入......但如果你在框中写字母就会出错......

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的分数?

3 个答案:

答案 0 :(得分:2)

这样的事情:

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例外。

答案 1 :(得分:0)

你可以做到

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()

答案 2 :(得分:0)

我建议使用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语句的一部分是详细的,函数不必知道。