Python While 迴圈語句

2021-10-01 06:10:13 字數 2913 閱讀 7734

python 程式設計中 while 語句用於迴圈執行程式,即在某條件下,迴圈執行某段程式,以處理需要重複處理的相同任務。其基本形式為:

while 判斷條件(condition):

執行語句(statements)……

執行語句可以是單個語句或語句塊。判斷條件可以是任何表示式,任何非零、或非空(null)的值均為true。

當判斷條件假 false 時,迴圈結束。

執行流程圖如下:

gif 演示 python while 語句執行過程

複雜一點:

例項

#!/usr/bin/python

count = 0

while

(count < 9):

print 'the count is:', count

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 i%2 > 0: # 非雙數時跳過輸出

continue

print i # 輸出雙數2、4、6、8、10

i = 1

while 1: # 迴圈條件為1必定成立

print i # 輸出1~10

i += 1

if i > 10: # 當i大於10時跳出迴圈

break

無限迴圈

如果條件判斷語句永遠為 true,迴圈將會無限的執行下去,如下例項:

例項

#!/usr/bin/python

# -*- coding: utf-8 -*-

var = 1

while var == 1 :

# 該條件永遠為true,迴圈將無限執行下去

num = raw_input(

"enter a number :"

) print "you entered: ", num

print "good bye!"

以上例項輸出結果:

enter a number  :20

you entered: 20

enter a number :29

you entered: 29

enter a number :3

you entered: 3

enter a number between :traceback (most recent call last):

file "test.py", line 5, in

num = raw_input(

"enter a number :"

)keyboardinterrupt

注意:以上的無限迴圈你可以使用 ctrl+c 來中斷迴圈。

迴圈使用 else 語句

在 python 中,while … else 在迴圈條件為 false 時執行 else 語句塊:

例項

#!/usr/bin/python

count = 0

while count < 5:

print count, " is less than 5"

count = count + 1

else:

print count, " is not less than 5"

以上例項輸出結果為:

0 is less than 5

1 is less than 5

2 is less than 5

3 is less than 5

4 is less than 5

5 is not less than 5

簡單語句組

類似 if 語句的語法,如果你的 while 迴圈體中只有一條語句,你可以將該語句與while寫在同一行中, 如下所示:

例項

#!/usr/bin/python

flag = 1

while

(flag): print 'given flag is really true!'

print "good bye!"

注意:以上的無限迴圈你可以使用 ctrl+c 來中斷迴圈。

Python While 迴圈語句

python 程式設計中 while 語句用於迴圈執行程式,即在某條件下,迴圈執行某段程式,以處理需要重複處理的相同任務。其基本形式為 while 判斷條件 執行語句 執行語句可以是單個語句或語句塊。判斷條件可以是任何表示式,任何非零 或非空 null 的值均為true。當判斷條件假false時,迴...

Python While迴圈語句

python while 迴圈語句 python 程式設計中while 語句用於迴圈執行程式,即在某條件下,迴圈執行某段程式,以處理需要重複處理的相同任務。其基本形式為 while 判斷條件 執行語句 執行語句可以是單個語句或語句塊。判斷條件可以是任何表示式,任何非零 或非空 null 的值均為 t...

python while迴圈語句

迴圈是程式語言中反覆執行某些 的一種計算機處理過程 重複執行某些 while 條件 反覆執行的 迴圈變數是用於控制迴圈執行次數的變數,通常從0開始計數。如果迴圈語句未設定合理的退出條件,則迴圈語句將構成死迴圈,程式將永久執行下去。break可以用於終止迴圈的執行,當執行到break語句後,程式將跳出...