while循環中break、continue的應用


循環語句

while循環

  • while True : (無限循環)

break : 跳出整個循環

continue : 跳過這次循環,進行下次循環(偽裝成循環體中最后一行)

  • # print(1111)
    # while True:   # 死循環
    #     print("堅強")
    #     print("過火")
    #     print("雞你太美")
    #     print("大碗寬面")
    # print(333)	--輸出結果 1111  堅強 過火 雞你太美 大碗寬面 堅強···*4 不會輸出333
    
    # count = 0
    # while True:  # 死循環
    #     count = count + 1  # 先執行 = 右邊的內容
    #     if count == 5:
    #         print(count)
    #         break # 有限循環	--輸出結果 5 循環4次(從0-3)
    
    # 輸出1,3,5,7,9
    
    # count = 1
    # while count < 10:
    #     print(count)
    #     count = count + 2
        
    # a = 0
    # while a < 10:
    #     a += 1
    #     if a % 2 == 0:
    #         continue
    #     else:
    #         print(a)
    
    # a=0
    # while a<3:
    #     a += 1
    #     print (a)
    #     continue
    # else:          #此處else意為平級的while a>=3:   !!!
    #     print(111)	---輸出結果為:1 2 3 111
    
    # print(222)
    # count = 0
    # while count < 3:
    #     print(count)
    #     count = count + 1
    # print(111)	---輸出結果為:222 0 1 2 111
    
    # print(222)
    # count = 0
    # while count < 3:
    #     print(count)
    #     count = count + 1
    #     break
    # print(111)	---運行結果 : 222 0 111
    
    # print(222)
    # count = 0
    # while count < 3:
    #     print(count)
    #     count = count + 1
    #     break
    # else:
    #     print(111)	---運行結果: 222 0   while-else是一個整體,break跳出是跳出整個循環
    

while else 體系

  • 當while的條件滿足或為True時,走while的結果,當while的條件不再滿足以后,走else的結果;當while條件不滿足或為False時,執行else。
  • 注意,無論何種情況,else的內容執行完后,隨即退出整個while-else體系
  • else中可以用到while循環體中的數據,但在pycharm中使用時會飄黃


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM