[英]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.