1.初識if判斷
判斷是一種能力,比如生活中天冷了就多穿衣服,下雨了就帶雨傘等等
讓程序擁有我們的判斷能力,如果程序…就執行…,這就用到了if判斷。
基本語法:
if 條件:
代碼塊1
如果條件成立,就執行代碼塊1,否則不執行
2.if判斷基本使用
注意事項:
1.出現了if和else,必然走一個
2.if可以嵌套,但最好不要超過3層
1.if else
需求:用戶輸入一個數,如果大於5打印’太大了’,否則打印’太小了’
user_input = int(input("請輸入(必須爲數字):"))
if user_input > 5:
print("太大了")
else:
print("太小了")
2.if elif else
需求:
分數 | 成績 |
---|---|
>= 90 | 優秀 |
80 <= score < 90 | 良好 |
70 <= score < 80 | 及格 |
< 70 | 不及格 |
用戶輸入成績,90以上爲優秀,80-90爲良好,70-80爲及格,70分以下爲不及格
score = int(input("請輸入分數:"))
if score >= 90:
print("你的成績是:優秀")
elif 80 <= score < 90:
print("你的成績是:良好")
elif 70 <= score < 80:
print("你的成績是:及格")
else:
print("你的成績是:不及格")