首页 > 解决方案 > 如何从此 python 代码中获得正确的输出?

问题描述

我有一个 python 代码,它无法获得正确的输出。代码如下所示:

score = int(input("Please input a score: "))
grade = ""
if score < 60:
    grade = "failed"
elif score < 80:     # between 60 and 80
    grade = "pass"
elif score < 90:
    grade = "good"
else:
    grade = "excellent"

print("score is (0), level is (1)".format(score,grade))

谁能告诉我问题出在哪里?太感谢了!

标签: python

解决方案


您应该将 if 语句更改为:

if score <= 60:
    grade = "failed"
elif score <= 80 and score > 60:     # between 60 and 80
    grade = "pass"
elif score <= 90 and score > 80:
    grade = "good"
elif score > 90: #Assuming there is no max score since before, you left the last statement as an else. 
    grade = "excellent"
else: #Not necessary but always nice to include.
    print("Not a valid score, please try again.")

而且,正如@loocid 评论的那样,更改print("score is (0), level is (1)".format(score,grade))print("score is {0}, level is {1}".format(score,grade))

虽然我更喜欢

print("score is " + str(score) + ", level is " + str(grade))


推荐阅读