我试图编写一个代码,只需输入你的测试分数(满分100分),它就会给你一个分数(A,B,C,D ..等)。但是,由于某种原因,我写的代码在给出一个随机数时给了我错误的分数。例如,我键入6,它给了我一个D(而不是U)。 这是我的代码:
score=int(input("What score did you get on your test?"))
if int(0)>=score<=int(39):
print ("You have got a U in your test.")
elif int(40)>=score<=int(49):
print ("You have got a D in your test.")
elif int(50)>=score<= int(59):
print ("You have got a C in your test.")
elif int(60)>=score<= int(69):
print ("You have got a B in your test.")
else:
("You have got an A in your test, well done!")
答案 0 :(得分:5)
你的不平等是不正确的。目前,U的条件是
if score is smaller than 0 and smaller than 39
应该是
if score is greater than 0 and smaller than 39
所以
if int(0) <= score <= int(39)
但是,正如其他人所指出的那样,您可以大量简化所有代码。您可以远程处理双边不等式并将其替换为单个不等式,删除int
条件,因为您不期望任何非整数(数字39,49等都是硬编码的),您还应该为0以下或100以上的等级添加某种错误消息(目前,它们分别返回U和A,但它确实应该是错误的。)
更好的解决方案:
score=int(input("What score did you get on your test?"))
if score < 0:
print("How did you manage to get less than zero?!")
elif score <= 39:
print ("You have got a U in your test.")
elif score <= 49:
print ("You have got a D in your test.")
elif score <= 59:
print ("You have got a C in your test.")
elif score <= 69:
print ("You have got a B in your test.")
elif score <= 100:
print ("You have got an A in your test, well done!")
else
print ("This isn't a valid grade, it should be between 0 and 100!")