python入門語句基礎之if語句、while語句
一、if語句
if 語句讓你能夠檢查程序的當前狀態(tài),并據(jù)此采取相應的措施。if語句可應用于列表,以另一種方式處理列表中的大多數(shù)元素,以及特定值的元素
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'),根據(jù)條件測試的值為 True 還是 False 來決定是否執(zhí)行 if 語句中的代碼。如果條件測試的值為True ,Python就執(zhí)行緊跟在 if 語句后面的代碼;如果為 False , Python 就忽略這些代碼,不執(zhí)行。
在Python中檢查是否相等時區(qū)分大小寫,例如,兩個大小寫不同的值會被視為不相等
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時才執(zhí)行操作;或者多個條件中,只滿足一個條件為True時就執(zhí)行操作,在這些情況下,可分別使用關鍵字and和or
ages=['73','12','60','1','10','55','13'] for age in ages: if age > str(60): #注意:ages中為列表字符串,所以age也是字符串,無法與整型的數(shù)字相比,需要先將數(shù)字轉化為字符串再比較。 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 循環(huán)用于針對集合中的每個元素都一個代碼塊,而 while 循環(huán)不斷地運行,直到指定的條件不滿足為止。
例如,while 循環(huán)來數(shù)數(shù)
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循環(huán),再執(zhí)行print(current_number)語句。
運行結果:
1
2
3
4
5
6
1、可以用來定義一個標志
定義一個變量,用于判斷整個程序是否處于活動狀態(tài)。這個變量被稱為標志,相當于汽車的鑰匙,鑰匙啟動時,汽車所有的電子設備、發(fā)動機、空調等均可正常運行,一旦鑰匙關閉時,整個汽車熄火狀態(tài),全部不能運行。
同理,程序在標志為 True 時繼續(xù)運行,并在任何事件導致標志的值為 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為真的時候,執(zhí)行程序, message = input(prompt) if message == 'quit': #當輸入信息為quit時,標志active為False,程序停止 active = False else: print(message)
2、使用 break 退出循環(huán),要立即退出 while 循環(huán),不再運行循環(huán)中余下的代碼
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、在循環(huán)中使用 continue
current_number = 0 while current_number < 10: current_number += 1 #以1逐步增加 if current_number % 2 == 0: #求模運行,是2的倍數(shù),為0 continue #忽略并繼續(xù)運行。 print(current_number) #打印出數(shù)字
4、使用 while 循環(huán)來處理列表和字典
1)處理列表中的數(shù)據(jù)
unconfirmed_users = ['Lucy', 'Bush', 'lincon', 'lucy', 'jack', 'lily', 'lucy', 'hanmeimei'] # 首先,創(chuàng)建一個待驗證用戶列表 confirmed_users = [] # 創(chuàng)建一個用于存儲已驗證用戶的空列表 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循環(huán)打印每個已驗證的用戶名 print(confirmed_user.title()) print("\n") # 刪除包含特定的所有列表元素 while 'lucy' in confirmed_users: # while 循環(huán),因為lucy在列表中至少出現(xiàn)了一次 confirmed_users.remove('lucy') # 刪除除最后一個外的其他相同的元素 print(confirmed_users)
運行結果如下:
Verifying user: Hanmeimei
Verifying user: Lucy
Verifying user: Lily
Verifying user: Jack
Verifying user: Lincon
Verifying user: Bush
The following users have been confirmed:
Hanmeimei
Lucy
Lily
Jack
Lincon
Bush
['hanmeimei', 'lily', 'jack', 'lincon', 'Bush', 'Lucy']#注意保留的是最后一個Lucy
2) 處理字典中的數(shù)據(jù)
responses = {}#定義一個空字典 polling_active = True # 設置一個標志,指出調查是否繼續(xù) 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中的名字)
到此這篇關于python入門語句基礎之if語句、while語句的文章就介紹到這了,更多相關python if語句while語句內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Django使用 Bootstrap 樣式修改書籍列表過程解析
這篇文章主要介紹了Django使用 Bootstrap 樣式修改書籍列表過程解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2019-08-08對Python中class和instance以及self的用法詳解
今天小編就為大家分享一篇對Python中class和instance以及self的用法詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-06-06python使用socket高效傳輸視頻數(shù)據(jù)幀(連續(xù)發(fā)送圖片)
本文主要介紹了python使用socket高效傳輸視頻數(shù)據(jù)幀(連續(xù)發(fā)送圖片),文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-10-10jupyter notebook 參數(shù)傳遞給shell命令行實例
這篇文章主要介紹了jupyter notebook 參數(shù)傳遞給shell命令行實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-04-04