好的,所以当我运行此代码并输入50例如它将列出其下的所有等级。我该如何解决?另外,我怎样才能提高效率呢?这是一个相当简单的任务的相当多的代码,我不知道如何实现它。感谢所有回复。
print("-------WELCOME-------")
testscore = int(input("What mark did you get?"))
if testscore>= 80:
print("You got an A!!")
else:
if testscore>= 70:
print("You got an B!")
if testscore>= 60:
print("You got an C.")
if testscore>= 50:
print("You got an D.")
if testscore>= 40:
print("You got an F.")
if testscore>= 30:
print("You got a G. Wow.")
if testscore<= 20:
print("There is nothing this low. Maybe you should have studied more? re-think your life please.")
second = input("do you want to get another test score?")
if second == "yes":
testscore = int(input("What mark did you get?"))
if testscore>= 80:
print("You got an A!!")
else:
if testscore<= 70:
print("You got an B!")
if testscore<= 60:
print("You got an C.")
if testscore<= 50:
print("You got an D.")
if testscore<= 40:
print("You got an F.")
if testscore<= 30:
print("You got a G. Wow.")
if testscore<= 20:
print("There is nothing this low. Maybe you should have studied more? re-think your life please.")
if second == "no":
print("Thanks for using MARK TO GRADE CONVERTER. See you soon!")
答案 0 :(得分:1)
问题是else
部分中的所有条件都是独立测试的。
if testscore>= 80:
print("You got an A!!")
else:
if testscore>= 70:
print("You got an B!")
if testscore>= 60:
print("You got an C.")
if ...
如果testscore
为75
,则第一个条件为真,因此执行print("You got an B!")
。然后测试第二个条件,这也是正确的,因此它执行print("You got an C!")
,依此类推。对于前两个条件(A和B),您使用了else: if ...
,它朝着正确的方向前进,但对所有条件使用else: if
会导致大量嵌套块。相反,除第一个条件外,您可以使用elif
。这样,只有前一个条件评估为false时才会测试下一个条件:
if testscore>= 80:
print("You got an A!!")
elif testscore>= 70:
print("You got an B!")
elif testscore>= 60:
print("You got an C.")
elif ...
类似的第二块if
语句进一步向下。 (比较在该块中是相反的,但实际上我猜这些块应该是相同的;在这种情况下,你应该使它成为一个函数并调用该函数两次而不是复制该代码。)
或者,您可以例如创建成绩和分数列表,然后在一行中找到满足条件的next
分数:
>>> grades = (('A', 80), ('B', 70), ('C', 60), ('D', 50), ('F', 0))
>>> score = 56
>>> next((g for g, n in grades if score >= n))
'D'
答案 1 :(得分:1)
如果您想减少代码并提高效率,可以使用dictionary
存储成绩并在成绩上使用整数divison来获取密钥,如下所示:
grades = {7:'B', 6:'C', 5:'D', 4:'F', 3:'G'}
testscore = int(input("What mark did you get?"))
if testscore>= 80:
print("You got an A!!")
elif testscore < 30:
print("There is nothing this low. Maybe you should have studied more? re-think your life please.")
else:
print("You got an " + grades[testscore // 10] + "!")
如果你想loop
,你可以使用:
loop = 'yes'
while loop == 'yes':
#code here
loop = raw_input('Do you want to get another test score?')