简体   繁体   English

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

[英]Cant get str to work in if-loop Python 3

I wrote a grade calculator where you put a float in and get a grade based on what you scored. 我写了一个成绩计算器,在其中您可以浮动并根据您的得分获得成绩。 The problem I have is that I belive I need a float(input... But that becomes an error if you write letters in the box... 我的问题是我相信我需要一个float(input ...但是如果您在框中输入字母,那将变成一个错误...

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

Is there a way to get rid of the float and print the last statement if you write something else that the score from 0-10? 如果您编写分数介于0到10之间的其他内容,是否有办法摆脱浮点并打印最后一条语句?

Something like this: 像这样:

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

Keep on asking until the float cast works without raising the ValueError exception. 继续询问直到float起作用而没有引发ValueError异常。

You could do 你可以做

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

I would suggest to use EAFP approach and separate handling good and bad inputs. 我建议使用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")

Note that typically you want to return from functions, not print inside them. 请注意,通常您要从函数返回,而不是在函数内部打印。 Using function output as part of print statement is detail, and function does not have to know that. 使用函数输出作为print语句的一部分很详细,函数不必知道这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM