文章目錄
第四章 if語句
4.1 條件測試
4.1.1 檢查是否相等
car = 'bmw'
print(car == 'bmw')
print(car == 'byd')
print(car != 'byd')
輸出結果:
True
False
True
==
等於!=
不等於>, >=, <, <=
大小於等於
4.1.2 檢查多個條件
car = 'bmw'
phone = 'iphone'
print(car == 'bmw' and phone == 'iphone')
print(car == 'byd' or phone == 'samsung')
True
False
and
邏輯且or
邏輯或
4.1.3 檢查特定值是否在列表中
nums = [10, 20, 30]
print(30 in nums)
print(40 not in nums)
True
True
in
在列表中not in
不在列表中
4.1.4 布爾表達式
flag = True
flag = False
不多贅述
4.2 if語句
age = 15
if age >= 18:
print("You are old enough")
print("You can vote now")
沒有輸出結果
Python的if語句不需要加括號。注意冒號
4.2.1 if-else語句
age = 15
if age >= 18:
print("You are old enough")
print("You can vote now")
else:
print("You are too young")
print("Please wait for " + str(18-age) + " year(s)")
輸出結果:
You are too young
Please wait for 3 year(s)
4.2.2 if-elif-else語句
age = 15
if age >= 18:
print("You are an adult")
elif age >= 12:
print("You are a teenager")
else:
print("You are a child")
輸出結果:
You are a teenager
4.2.3 檢查列表是否爲空
nums = []
if nums:
print("list is not empty")
else:
print("list is empty")
輸出爲:
list is empty
4.2.4 if語句與布爾表達式
flag = True
if flag:
print("YES")
else:
print("NO")
輸出:
YES
不多贅述