條件測試
1. 檢查是否相等
一個等號表示賦值,兩個等號用於判斷等號左右兩邊是否相等,返回值為True或者False.
2. 檢查是否相等是需考慮大小寫
大小寫不同的值視為不相等,例如繼續寫入代碼:car == 'Bmw',返回:False
此時就可引用lower()或者upper()函數進行字符串大小寫的轉換,方便比較。
3. 檢查是否不相等
與判斷是否相等類似,不過是將第一個等號用感嘆號替換,即:!= 表示不等運算符。
4. 其他條件判斷
除了等於和不等之外,還可比較兩者是否大於(>)、大於等於(>=)、小於(<)、小於等於(<=)。
5. 判斷多個條件
可用關鍵字and或or將兩個單獨的條件判斷合二為一:
6. 檢查特定值是否在列表中
7. 布爾表達式
給變量賦值為True或False,eg: edit = True
if語句
1. 簡單的if語句
# 判斷是否達到投票的年齡 age = 19 if age >= 18: print('You are old enough to vote!')
2. if-else語句
age = 17 if age >= 18: print('You are old enough to vote!') else: print('Sorry, you are too young to vote yet.')
3. if-elif-else語句
age = 12 if age < 4: print('Your admission cost is 0 yuan.') elif age < 18: print('Your admission cost is 5 yuan.') else: print('Your admission cost is 10 yuan.')
上述的代碼中有3條打印語句,有點繁瑣,也可簡化為:
if age < 4: price = 0 elif age < 18: price = 5 else: price = 10 print('Your admission cost is ' + str(price) + ' yuan.') # 用str()將數字轉換為字符型,否則會因類型不一致報錯
4. 使用多個elif代碼塊
if age < 4: price = 0 elif age < 18: price = 5 elif age < 65: price = 10 else: price = 5
5. else代碼塊可以省略
用代碼 elif age >= 65: 替換 else:
6. 多個條件
require_foods = ['pizza', 'falafel', 'carrot cake'] if 'pizza' in require_foods: print('Adding pizza') if 'falafel' in require_foods: print('Adding falafel') elif 'carrot cake' in require_foods: print('Adding carrot cake') print('This is you need.')
運行結果:
Adding pizza
Adding falafel
This is you need.
代碼塊中有多個if語句時,每個if語句都執行;但若是if-elif-else結構,代碼運行時從前往后依次執行,一旦有條件滿足,將不再執行后邊的判斷語句。
if語句處理列表
1. 檢查特殊元素
for require_food in require_foods: if require_food == 'carrot cake': # 判斷需求是否存在 print('Sorry, we are out of carrot cake now.') # 打印供給不足 else: print('Adding ' + require_food)
判斷需求是否存在,存在則添加,不存在則抱歉。
2. 確定列表是否為空
require_foods = [] if require_foods: for require_food in require_foods: print('Adding ' + require_food) else: print('Are you sure nothing you want?')
運行結果:
Are you sure nothing you want?
沒有需求時確認一下
3. 使用多個列表
menu_lists = ['pizza', 'falafel', 'carrot cake', 'cannoli', 'ice cream'] want_eats = ['falafel', 'carrot cake', 'ice cream'] for want_eat in want_eats: if want_eat in menu_lists: print('Adding ' + want_eat) else: print('Sorry, we does not have ' + want_eat + '.')
點餐時添加菜單中有的,對於沒有的表示抱歉。