python if語句使用

#if語句
#if語句可以沒有小括號,大括號用冒號替代
#例:以下輸出如果car不等於bmw或不等於subaru且等於audi就大寫輸出,
#與其它語言語法基本一樣,或用的是or且用的是and,大括號用的是冒號.
cars = ['audi','bmw','subaru','toyota']
for car in cars:
if (car != 'bmw' or car != 'subaru') and car == 'audi':
print(car.upper())
else:
print(car.title())
#判斷特定值是否在列表中存在
#檢查特定值是否包含在列表中,判斷包含用in,不包含用not in 
#例:
car = 'benz'
if car not in cars:
print("存在")
else:
print("不存在")
if car in cars:
print("存在")
else:
print("不存在")

#檢查超過兩個判斷的情形就要用到if elif else 結構 其它與別的語法基本一致,就注意elif寫法
#if使用小技巧,如果你只想執行一個代碼塊,就用if elif else情況(else不是必須的)如果想執行多個就用一系列獨立if
#例:
age = 40
if age <= 17:
print("小屁孩");
elif age >= 18 and age <= 30:
print("小夥子")
else:
print("年齡超大")

#判斷列表是否爲空
例:
requested_toppings = []
print(requested_toppings)
if requested_toppings:
print("不爲空")
else:
print("爲空")
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章