時間:2025.7.18
學習內容:【語法基礎】if判斷、比較運算符與邏輯運算符
一、if判斷
if判斷基本格式:if要判斷的條件,條件成立時要做的事情
注意:input內默認存儲的是字符串
age=17
if age<18:print('未成年不能上網')
score=input('你的成績:')
if score == 100://輸入100或60無對應的文字顯示print('你真棒!')
if score==60:print('還要繼續加油哦!')
age=17
if age<18:print('未成年不能上網')
score=input('你的成績:')
if score == '100':print('你真棒!')
if score=='60':print('還要繼續加油哦!')
二、運算符
比較運算符 == != > < >= <= 邏輯運算符 and(與) or(或) not(非) 三目運算符(三元表達式) 為真結果 if判斷條件 else為假結果
==比較的是兩個變量的值是否相等,相等的話就返回為True(真),不相等就返回為False(假)
and 左右兩邊都為真才為真
or 左邊或右邊有一個為真即為真
not取反,表示相反的結果
a=5
b=8
if a<b:print('a比b小')
else:print('a不比b小')
#三目運算符寫法
print('a比b小') if a<b else print('a不比b小')
三、if-else
基本格式
if-else二選一;if-elif多選一
注意:格式與C語言寫法不同
score=45
if 85<=score<=100:print('優秀')
elif 60<=score<85:print('良好')
elif 0<=score<60:print('不及格')
else:print('分數無效')
四、if嵌套
if嵌套的基本格式
ticket=True
tem=38.5
if ticket==True:print('可以進站')if(36.3<=tem<=37.2):print('體溫正常')else:print('體溫異常')
else:print('沒票不能進站')