示例
cars = ['audi', 'bmw', 'subaru', 'toyota']
for car in cars:
if car == 'bmw':
prinit(car.upper())
else:
print(car.title())
條件測(cè)試
檢查是否相等
使用==會(huì)返回一個(gè)布爾值。
檢查相等時(shí)不考慮大小寫
Python中檢查是否相等時(shí)區(qū)分大小寫:
car = 'Audi'
car == 'audi' # False
如果要不區(qū)分大小寫,可以將值都轉(zhuǎn)化為小寫,使用lower(),且這種方式不會(huì)修改原值。
檢查是否不相等
使用!=即可,和大多數(shù)語言一樣。
比較數(shù)字
可以使用許多數(shù)學(xué)比較,<,<=,>,>=。
檢查多個(gè)條件
使用關(guān)鍵字and,和or
- 使用and
and左右兩個(gè)條件都為Tue,那么結(jié)果為True:
age_0 >= 21 and age_1 >=21
2.使用or
只要有一個(gè)條件為True,結(jié)果就為True,反之為False:
age_0 >=21 or age_1 >= 21
檢查特定值是否包含在列表中
要判斷特定值是否已包含在列表中,可使用關(guān)鍵字in:
requested_toppings = ['mushrooms', 'onions','pineapple']
'mushrooms' in requested_toppings # True
檢查特定值不包含在列表中
使用not in:
banned_user = ['andrew', 'carolina', 'david']
user = 'marie'
if user not in banned_users:
print(user.title() + ', you can post a response if you wish.')
if語句
簡(jiǎn)單的if語句:
if conditional_test:
do something
if-else語句
age = 17
if age >= 18:
prinit('you are old enough.')
else:
print('sorry, you are too young to vote.')
if-elif-else語句
age = 12
if age < 4:
print('Your admission cost is $0.')
elif age < 18:
print('Your admission cost is $5.')
else:
print('Your aimission cost is $10.')
可以使用多個(gè)elif,也可以省略else。
使用if語句處理列表
確定列表不是空的
requested_toppings = []
if requested_toppings:
do something
如果列表為空,if語句處會(huì)返回False。