- 一個簡單示例
cars = ['audi','bmw','toyota']
for car in cars:
if car == 'bmw':
print(car.upper())
else:
print(car.title())
- 條件測試
每條if 語句的核心都是一個值爲True 或False 的表達式,這種表達式被稱爲條件測試 。
1、檢查是否相等
將變量當前值與特定值進行比較。
2、檢查是否相等時不考慮大小寫
當大小寫不是很重要,可將變量的值轉換爲小寫後比較。
3、檢查是否不相等
判斷兩個值是否不相等,可結合使用感嘆號和等號(!=);!表示 不 。
4、比較數字
age = 18
if age == 18:
print(age == 18)
5、檢查多個條件
and or
6、檢查特定值是否包含在列表中
requested_toppings = ['mushrooms', 'onions', 'pineapple']
if 'mushrooms' in requested_toppings:
print('mushrooms' in requested_toppings)
7、檢查特定值是否不包含在列表中
not in
banned_users = ['andrew', 'carolina', 'david']
user = 'marie'
if user not in banned_users:
print(user.title() + ",you can post a response if you wish.")
8、布爾表達式
條件測試的別名
- if 語句
age = 19
if age >= 18:
print("You are old enough to vote!")
print("Have you registered to vote yet?")
age = 17
if age >= 18:
print("You are old enough to vote!")
print("Have you registered to vote yet?")
else:
print("Sorry, you are too young to vote.")
print("Please register to vote as soon as you turn 18!")
age = 12
if age < 4:
print("Your admission cost is $0.")
elif age < 18:
print("Your admission cost is $5.")
else:
print("Your admission cost is $10.")
- 使用 if 語句處理列表
1、檢查特殊元素
requested_toppings = ['mushrooms', 'green peppers', 'extra cheese']
for requested_topping in requested_toppings:
if requested_topping == 'green peppers':
print("Sorry, we are out of green peppers right now.")
else:
print("Adding " + requested_topping + ".")
print("\nFinished making your pizza!")
2、確定列表不是空
requested_toppings = []
if requested_toppings:
for requested_topping in requested_toppings:
print("Adding " + requested_topping + ".")
print("\nFinished making your pizza!")
else:
print("Are you sure you want a plain pizza?")
3、使用多個列表
available_toppings = ['mushrooms', 'olives', 'green peppers', 'pepperoni', 'pineapple', 'extra cheese']
requested_toppings = ['mushrooms', 'french fries', 'extra cheese']
for requested_topping in requested_toppings:
if requested_topping in available_toppings:
print("Adding " + requested_topping + ".")
else:
print("Sorry, we don't have " + requested_topping + ".")
print("\nFinished making your pizza!")
- 設置 if 語句的格式
在條件測試的格式設置方面,PEP 8提供的唯一建議是,在諸如== 、>= 和<= 等比較運算符兩邊各添加一個空格,例如,if
age < 4: 要比if age<4: 好。 這樣的空格不會影響Python對代碼的解讀,而只是讓代碼閱讀起來更容易。