[英]if statement\how to loop problems
好的,所以当我运行此代码并放入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!")
问题在于, else
部分中的所有这些条件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
,则第一个条件为true,因此执行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'
如果要减少代码并提高效率,可以使用dictionary
来存储等级,并在等级上使用整数除法来获取密钥,如下所示:
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?')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.