python—If else


按照100分制,90分以上的成績為A。,80~90為B,60~80為C,60以下為D。編寫程序,當用戶輸入分數時,自動轉換生成ABCD等級。

score = int(input('請輸入一個分數:'))
if 100>=score>=90:
    Print('A')
if 90>score>=80:
    Print('B')
if 80>score>=60:
    Print('C')
if 60>score>=0:
    Print('D')
if score < 0 or score > 100:
    print('輸入錯誤!')

  也可以寫成:

score = int(input('請輸入一個分數:'))
if 100>=score>=90:
    Print('A')
else:
    if 90>score>=80:
        Print('B')
    else:
         if 80>score>=60:
            Print('C')
         else:
            if 60>score>=0:
                print('D')
            else:
                print('輸入成績錯誤!')

  當條件過多的時候,可以考慮第三種方法

score = int(input('請輸入一個分數:'))
if 100>=score>=90:
    Print('A')
elif 90>score>=80:
    Print('B')
elif 80>score>=60:
    Print('C')
elif 60>score>=0:
    Print('D')
else:
    print('輸入成績錯誤!')

  Python的縮進使用強制規定使得代碼必須正確對齊,讓程序員來決定else到底屬於哪一個if。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM