Python While 循環語句

Python While循環語句python

    Python 編程中while語句用於循環執行程序,即在一些條件下,循環執行一些段程序,以處理須要重複處理的相同任務。編程

     執行語句能夠是單個語句或語句塊。ide

     判斷條件能夠是任何表達式,任何非零、或非空(null)的值均爲true。oop

     當判斷條件假false時,循環結束。url

         python_while_loop

實例spa

       #!/usr/bin/pythoncode

         count = 0it

         while ( count < 9):io

                 print 'The count is:', countclass

                 count = count +1

         print " Good bye!"

以上代碼執行輸出結果:

    

The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8
Good bye!

 while語句還有另外兩個重要的命令 continue,break 來跳過循環。

  • continue 用於跳過該次循環。

  • break 則用於退出循環,此外「判斷條件」還能夠是個常值,表示循環一定成立。

具體操做以下:

    # continue 和break 用法:

    i = 1

    while i < 10:

           i + = 1

           if 1%2 >0:    # 非雙數時跳過輸出

                continue

    print i      # 輸出雙數二、四、六、八、10

i = 1

while = 1:     # 循環條件爲1一定成立

    print i

    i + = 1

    if i > 10:    # 當i大於10時跳出循環

        break

相關文章
相關標籤/搜索