網站首頁 編程語言 正文
一、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: Lincon
Verifying user: Bush
The following users have been confirmed:
Hanmeimei
Lucy
Lily
Jack
Lincon
Bush
['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.cnblogs.com/codingchen/archive/2022/04/24/16133182.html
相關推薦
- 2022-09-22 get方法和post方法的區別
- 2022-03-06 Android中SurfaceFlinger工作原理_Android
- 2022-06-10 C語言中sizeof函數踩過的坑總結_C 語言
- 2023-03-18 go?sync.Map基本原理深入解析_Golang
- 2023-05-15 golang判斷結構體為空的問題_Golang
- 2023-03-03 PostgreSQL實時查看數據庫實例正在執行的SQL語句實例詳解_PostgreSQL
- 2022-07-21 React中this指向問題
- 2023-01-08 react?頁面加載完成后自動執行標簽的點擊事件的兩種操作方法_React
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支