日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Python學習筆記嵌套循環詳解_python

作者:云風星月皆待卿 ? 更新時間: 2022-09-10 編程語言

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

欄目分類
最近更新