Python07 cycle

loop statement

  • A Brief Discussion: Repeat thing
  • Note: Set the stop cycling conditions, otherwise it will turn into an endless loop
  • for ... in ... loop, indescribed in more iterables (e.g.: list, tuple, string, ...)
    • grammar: for 变量名 in list:
    • Example:

      list = [1,3,"Go",'Java','''Python''']
      for list_value in list:
          print(list_value)
    • operation result:
      mQjlo6.png
  • range () function: generating a sequence of integer numbers of iterations may be
    • Example:

      # range() 函数
      rnumber1 = range(4) # 生成0-3之间(含 0,3)的数
      for i in rnumber1:
          print(i)
      number2 = range(1,3) # 生成 1-2 之间(含 1,2)的数
      for n in number2:
          print(n)
    • operation result:
      mQvL8S.png
  • while loop: to meet the conditions will cycle
    • grammar: while 条件:
    • Example:

      var1 = 2
      while var1 > 0:
      print(var1)
      var1 -= 1  # 等同于 var1 = var - 1
    • operation result:
      mQzuLj.png
    • break、continue
      • break: out of the loop body
      • Example:

        # break : 跳出循环语句
          var2 = 10
          while var2 < 15:
              print(var2)
              var2 += 1
              if var2 == 12: # 如果var2 的值等于 12,执行break,跳出循环即结束循环
                  break  
      • operation result:
        mlSBuQ.png
    • continue: the end of the cycle, to enter the next cycle
      • Example:
        # continue 结束此次循环,进入下次循环 var3 = 1 while var3 < 10: var3 += 1 if var3 == 5:# 当var3 等于 5的时候,执行continue,跳出此次循环,即不执行打印var3,进入下次循环 continue print(var3)
      • operation result:
        mlpLon.png
    • Infinite loop:
      • Example:
        while True: print("停不下来,哈哈哈")
      • Results: will always print停不下来,哈哈哈

Guess you like

Origin www.cnblogs.com/thloveyl/p/11374141.html