1. 程式人生 > >05-Python-if語句

05-Python-if語句

users xtra 是否 () car [] 滿足 核心 room

1、條件測試

每條if語句的核心都是一個值為True或False的表達式,這種表達式被稱為條件測試。Python根據條件測試的值為True還是False來決定是否執行if語句中的代碼。條件測試為True,則執行;否則,不執行。

1.1、檢查特定值是否包含在列表中

1 banned_users = [andrew,carolina,david]
2 user = marie
3 
4 if user in banned_users:
5     print(user.title() + ", you can post a response if you wish.")
6 if
user not in banned_users: 7 print(user.title() + " doesn‘t exist in list.")

1.2、布爾表達式

布爾表達式結果要麽為True,要麽為False。空字符串、列表、元組、字典等都為假。

1 bool([])  #值為False
2 bool({}) #值為False
3 bool([])   #值為False
4 bool("")  #值為False
5 bool(0)   #值為False
6 
7 bool(1)   #值為True
8 bool(-1)  #值為True

1.3、if-elif-else

 1 if <條件判斷1>:
 2     <執行1>
 3 elif <條件判斷2>:
 4     <執行2>
 5 elif <條件判斷3>:
 6     <執行3>
 7 else:
 8     <執行4>
 9 
10 #舉例
11 age = int(input("please input your age: "))
12 
13 if age < 4:  #4歲以下免費
14     price = 0
15 elif age < 18:  #4~17歲5塊
16     price = 5
17
elif age < 65: #18~64歲10塊 18 price = 10 19 else: #大於等於65歲的半價 20 price = 5 21 22 print("Your admission cost is $" + str(price) + ".")

1.4、測試多個條件

if-elif-else功能強大,但僅適合用於只有一個條件滿足的情況:遇到通過了的測試後後,Python會跳過余下的測試。如果有時候需要關心所有的檢測條件,則不能使用if-elif-else這種結構,而應該使用多個if語句。

 1 #如果顧客點了兩種配料,就需要確保在其披薩中包含‘mushrooms‘和‘extra cheese‘。
 2 requested_toppings = [mushrooms,extra cheese]
 3 
 4 if mushrooms in requested_toppings:
 5     print("Adding mushrooms.")
 6 if pepperoni in requested_toppings:
 7     print("Adding pepperoni.")
 8 if extra cheese in requested_toppings:
 9     print("Adding extra cheese:")
10 
11 print("\nFinished making your pizza!")

2、用if語句處理列表

2.1、處理特殊元素

1 requested_toppings = [mushrooms,green peppers,extra cheese]
2 
3 for requested_topping in requested_toppings:
4     if requested_topping == green peppers:  #如果點了青椒,則打印青椒沒了。
5         print("Sorry,we are out of green peppers right now.")
6     else:
7         print("Adding " + requested_topping + ".")
8 
9 print("\nFinished making your pizza!")

2.2、確定列表不是空的

1 requested_toppings = []
2 
3 if requested_toppings:  #為真就執行循環體
4   for requested_topping in requeted_toppings: 
5      print("Adding " + requested_topping + ".")
6   print("\nFinished making your pizza!")
7 else:
8   print("You get a plain pizza!")

2.3、使用多個列表

 1 available_toppings = [mushrooms,olives,green peppers,pepperoni,pineapple,extra cheese]
 2 requested_toppings = [mushrooms,french fries,extra cheese]
 3 
 4 for requested_topping in  requested_toppings:
 5     if requested_topping in available_toppings:
 6         print("Adding " + requested_topping + ".‘)
 7     else:
 8         print("Sorry, we don‘t have " + requested_topping + ".")
 9 
10 print("\nFinished making your pizza!")

05-Python-if語句