一、if陳述句
if 陳述句讓你能夠檢查程式的當前狀態,并據此采取相應的措施,if陳述句可應用于串列,以另一種方式處理串列中的大多數元素,以及特定值的元素
1、簡單示例
names=['xiaozhan','caiyilin','zhoushen','DAOlang','huangxiaoming'] for name in names: if name == 'caiyilin': #注意:雙等號'=='解讀為“變數name的值是否為'caiyilin' print(name.upper()) else: print(name.title())
每條if陳述句的核心都是一個值為 True 或 False 的運算式,這種運算式被稱為條件測驗(如上述條件 name == 'caiyilin'),根據條件測驗的值為 True 還是 False 來決定是否執行 if 陳述句中的代碼,如果條件測驗的值為True ,Python就執行緊跟在 if 陳述句后面的代碼;如果為 False , Python 就忽略這些代碼,不執行,
在Python中檢查是否相等時區分大小寫,例如,兩個大小寫不同的值會被視為不相等
my_fav_name = 'daolang' for name in names: if name == my_fav_name: print('Yes') print('No') print('\n') for name in names: if name.lower() == my_fav_name: print('Yes') print('No') print('\n') #下方使用 if……else陳述句 for name in names: if name.lower() != my_fav_name: #檢查是否不相等 print('NO') else: print('YES')
查多個條件:有時候需要兩多個條件都為True時才執行操作;或者多個條件中,只滿足一個條件為True時就執行操作,在這些情況下,可分別使用關鍵字and和or
ages=['73','12','60','1','10','55','13'] for age in ages: if age > str(60): #注意:ages中為串列字串,所以age也是字串,無法與整型的數字相比,需要先將數字轉化為字串再比較, print("The "+str(age)+" years has retired!") elif age > str(18) and age<=str(60): #兩個條件都為True時 print("The "+str(age)+" years is an Adult!") elif age > str(12): print("The "+str(age)+" years is a student!") else: print("The "+str(age)+" years is a child!")
二、while陳述句
for 回圈用于針對集合中的每個元素都一個代碼塊,而 while 回圈不斷地運行,直到指定的條件不滿足為止,
例如,while 回圈來數數
current_number = 1 while current_number <= 5: print(current_number) current_number += 1 print("\n") print(current_number)
當x<=5時,x自動加1,直到大于5時(也即current_number=6),退出while回圈,再執行print(current_number)陳述句,
運行結果:
1 2 3 4 5 6
1、可以用來定義一個標志
定義一個變數,用于判斷整個程式是否處于活動狀態,這個變數被稱為標志,相當于汽車的鑰匙,鑰匙啟動時,汽車所有的電子設備、發動機、空調等均可正常運行,一旦鑰匙關閉時,整個汽車熄火狀態,全部不能運行,
同理,程式在標志為 True 時繼續運行,并在任何事件導致標志的值為 False 時讓程式停止運行,
prompt = "\nTell me your secret, and I will repeat it back to you:" prompt += "\nEnter 'quit' to end the program. " active = True #定義一個標志 while active: #當active為真的時候,執行程式, message = input(prompt) if message == 'quit': #當輸入資訊為quit時,標志active為False,程式停止 active = False else: print(message)
2、使用 break 退出回圈,要立即退出 while 回圈,不再運行回圈中余下的代碼
prompt = "\nPlease enter the name of a city you have visited:" prompt += "\n(Enter 'quit' when you are finished.) " while True: city = input(prompt) if city == 'quit': break else: print("I'd love to go to " + city.title() + "!")
3、在回圈中使用 continue
current_number = 0 while current_number < 10: current_number += 1 #以1逐步增加 if current_number % 2 == 0: #求模運行,是2的倍數,為0 continue #忽略并繼續運行, print(current_number) #列印出數字
4、使用 while 回圈來處理串列和字典
1)處理串列中的資料
unconfirmed_users = ['Lucy', 'Bush', 'lincon', 'lucy', 'jack', 'lily', 'lucy', 'hanmeimei'] # 首先,創建一個待驗證用戶串列 confirmed_users = [] # 創建一個用于存盤已驗證用戶的空串列 while unconfirmed_users: # 驗證每個用戶,直到沒有未驗證用戶為止 current_user = unconfirmed_users.pop() # 注意pop()是從最后一個開始, print("Verifying user: " + current_user.title()) # 列印驗證的用戶,且首字母大寫 confirmed_users.append(current_user) # 將每個經過驗證的串列都移到已驗證用戶串列中, # 相當于將unconfirmed_users倒序保存到current_user中 print("\nThe following users have been confirmed:") # 顯示所有已驗證的用戶 for confirmed_user in confirmed_users: # for回圈列印每個已驗證的用戶名 print(confirmed_user.title()) print("\n") # 洗掉包含特定的所有串列元素 while 'lucy' in confirmed_users: # while 回圈,因為lucy在串列中至少出現了一次 confirmed_users.remove('lucy') # 洗掉除最后一個外的其他相同的元素 print(confirmed_users)
運行結果如下:
Verifying user: Hanmeimei
Verifying user: Lucy
Verifying user: Lily
Verifying user: Jack
Verifying user: Lucy
Verifying user: Lincon
Verifying user: Bush
Verifying user: Lucy
The following users have been confirmed:
Hanmeimei
Lucy
Lily
Jack
Lucy
Lincon
Bush
Lucy
['hanmeimei', 'lily', 'jack', 'lincon', 'Bush', 'Lucy']#注意保留的是最后一個Lucy
2) 處理字典中的資料
responses = {}#定義一個空字典
polling_active = True # 設定一個標志,指出調查是否繼續
while polling_active:
name = input("\nWhat is your name? ") # 提示輸入被調查者的名字和回答
response = input("Which mountain would you like to climb someday? ")
responses[name] = response # 將答卷存盤在字典中,即name是key,變數response 是值
repeat = input("Would you like to let another person respond? (yes/ no) ")# 看看是否還有人要參與調查
if repeat == 'no': #如無人參與調查,將標志設定為False,退出運行,
polling_active = False
# 調查結束,顯示結果
print("\n--- Poll Results ---")
print(responses) #把字典列印出來
for name, response in responses.items(): #訪問字典
print(name.title() + " would like to climb " + response + ".")
運行結果:
What is your name? lilei
Which mountain would you like to climb someday? siguliang
Would you like to let another person respond? (yes/ no) yes
What is your name? Lucy
Which mountain would you like to climb someday? The Alps
Would you like to let another person respond? (yes/ no) no
--- Poll Results ---
{'lilei': 'siguliang', 'Lucy': 'The Alps'}
Lilei would like to climb siguliang.
Lucy would like to climb The Alps.
實際運行:(為顯示全,已洗掉部分unconfirmed_users中的名字)

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/463466.html
標籤:其他
上一篇:執行緒有哪些狀態呢?
