引入:if-else的作用,滿足一個條件做什麼,否則做什麼。
if-else語句語法結構
if 判斷條件:
要執行的代碼
else:
要執行的代碼
判斷條件:一般爲關係表達式或bool類型的值
執行過程:程序運行到if處,首先判斷所帶的條件,如果條件成立,就是返回值是True,則執行下面的代碼;如果條件不成立則返回值是False, 則繼續執行下面的代碼。
示例1:模擬用戶登錄
提示輸入用戶名和密碼
如果用戶名是Admin,密碼等於123.com, 提示用戶登錄成功
如果用戶名不是Admin,提示用戶不存在
如果密碼不等於123.com, 提示密碼錯誤
username = input("請輸入用戶名:")
password = input("請輸入密碼:")
if username.lower().strip() == "admin" and password == "123.com":
print("登錄成功!")
else:
print("用戶名或者密碼錯誤!")
# lower()--把字符串轉爲小寫 upper()--把字符串轉爲大寫
# strip()--去除字符串前後的空格
結果:
C:\python\python.exe C:/python/demo/file2.py
請輸入用戶名: ADMIN
請輸入密碼:123.com
登錄成功!
Process finished with exit code 0
示例2:
在控制檯應用程序中輸入小王(語文,英語,數學)成績(單科滿分100分)
判斷:
1)如果所有科目都及格了,提示:恭喜你,你所有科目都通過考試了
2)否則提醒:很遺憾,你沒有通過考試,需要補考(沒有及格的名稱)
chinese = int(input("請輸入語文成績:"))
maths = int(input("請輸入數學成績:"))
english = int(input("請輸入英語成績:"))
get_course = ""
if chinese >= 60 and maths >= 60 and english >= 60:
print("恭喜你,所有科目都通過考試!")
else:
if chinese <= 60:
get_course += "語文、"
if maths <= 60:
get_course += "數學、"
if english <= 60:
get_course += "英語、"
print("很遺憾,你沒有通過考試,補考科目爲:" + get_course)
結果:
C:\python\python.exe C:/python/demo/file2.py
請輸入語文成績:54
請輸入數學成績:89
請輸入英語成績:32
很遺憾,你沒有通過考試,補考科目爲:語文、英語、
Process finished with exit code 0
示例3:(之前小紅花案例第一次優化)
在控制檯應用程序中輸入小王(語文,英語,數學)成績(單科滿分100分)
判斷:
1)如果有一門是100分
2)如果有兩門大於90分
3)如果三門大於80分
滿足以上一種情況,則獎勵一朵小紅花
chinese = int(input("請輸入語文成績:"))
maths = int(input("請輸入數學成績:"))
englist = int(input("請輸入英語成績:"))
get_course = ""
if (chinese == 100 or maths == 100 or englist == 100):
if(chinese == 100): get_course += "語文、"
if(maths == 100): get_course += "數學、"
if(englist == 100): get_course += "英語、"
print("你的%s得了100分,獎勵一朵小紅花❀!" % get_course)
else:
if(chinese >= 90 and maths >= 90) or (chinese >= 90 and englist >= 90) or (maths >= 90 and englist >= 90):
if(chinese >= 100): get_course += "語文、"
if(maths >= 90): get_course += "數學、"
if(englist >= 90): get_course += "英語、"
print("你的%s大於90分,獎勵一朵小紅花❀!" % get_course)
else:
if(chinese >= 80 and maths >= 80 and englist >= 80):
print("你的三個科目語文、數學、英語都大於80分,獎勵一朵小紅花❀")
結果:
C:\python\python.exe C:/python/demo/file2.py
請輸入語文成績:86
請輸入數學成績:98
請輸入英語成績:87
你的三個科目語文、數學、英語都大於80分,獎勵一朵小紅花❀
Process finished with exit code 0