網站首頁 編程語言 正文
1. 嵌套循環
- 多重循環
- 代碼測試1:
# 嵌套循環
def test():
for i in range(5):
for j in range(6):
print(f"{i} ", end='')
print('') # 換行
# Main
if __name__ == '__main__':
test()
代碼測試2:
# 九九乘法表
def test2():
for i in range(1, 10):
for j in range(1, i):
# print(f"{i}*{j}={i * j}", end=' ')
print("{0}*{1}={2}".format(i, j, i*j), end=' ')
print("")
# Main
if __name__ == '__main__':
test2()
代碼測試3:
# 表格
def test3():
staff1 = dict(name='高小一', age=20, salary=30000, city='北京')
staff2 = dict(name='高小二', age=19, salary=20000, city='上海')
staff3 = dict(name='高小幺', age=18, salary=10000, city='深圳')
table = [staff1, staff2, staff3]
for x in table:
if x.get("salary") > 15000:
print(x)
# Main
if __name__ == '__main__':
test3()
2. break語句
- break語句用于while和for循環,用來結束整個循環。
- 當有嵌套循環時,break語句只能跳出最近一層的循環。
while True:
if 退出條件:
break
3. continue語句
- continue語句用于結束本次循環,繼續下一次。
- 多個循環嵌套時,continue也是應用于最近的一層循環。
4. else語句
while, for 循環可以附帶一個else語句(可選)。如果for,while語句沒有被break語句結束,則會執行else字句,否則不執行。語法格式如下:
while 條件表達式:
循環體
else:
語句塊
for 變量 in 可迭代對象:
循環體
else:
語句塊
5. 循環代碼優化
三個原則提高代碼的運行效率:
- 盡量減少循環內部不必要的計算;
- 嵌套循環中,盡量減少內層循環的計算;
- 局部變量查詢較快,盡量使用局部變量;
原文鏈接:https://blog.csdn.net/Code_peasant/article/details/125827043
相關推薦
- 2024-02-27 idea中xml文件用瀏覽器打開
- 2022-10-03 Pandas中inf值替換的方法_python
- 2022-09-06 python?numpy中array與pandas的DataFrame轉換方式_python
- 2022-03-15 request doesn‘t contain a multipart/form-data or m
- 2022-08-14 C#生成比較短的Token字符串_C#教程
- 2023-03-16 Python?asyncio異步編程簡單實現示例_python
- 2022-04-02 .Net使用SuperSocket框架實現WebSocket前端_實用技巧
- 2023-06-17 C語言string庫strcpy、strcmp、strcat函數的使用_C 語言
- 最近更新
-
- 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同步修改后的遠程分支