新聞中心
Python 使用while和作為關鍵字來構成一個條件循環(huán),通過這個循環(huán)重復執(zhí)行一個語句塊,直到指定的布爾表達式為真。

以下是 while循環(huán)語法。
Syntax:
while [boolean expression]:
statement1
statement2
...
statementN
Python 關鍵字 while 有一個條件表達式,后跟:符號,以增加縮進開始一個塊。 該塊有要重復執(zhí)行的語句。這樣的塊通常被稱為循環(huán)體。身體將繼續(xù)執(zhí)行,直到情況評估為True。如果結果是False,程序?qū)⑼顺鲅h(huán)。 以下示例演示了 while循環(huán)。
Example: while loop
num =0
while num < 5:
num = num + 1
print('num = ', num) Output
num = 1
num = 2
num = 3
num = 4
num = 5在這里,while 語句之后的重復塊包括遞增一個整型變量的值并打印它。在塊開始之前,變量 num 被初始化為 0。直到它小于 5,num 遞增 1 并打印出來以顯示數(shù)字序列,如上所示。
循環(huán)體中的所有語句必須以相同的縮進開始,否則會引發(fā)IndentationError。
Example: Invalid Indentation
num =0
while num < 5:
num = num + 1
print('num = ', num) Output
print('num = ', num)
^
IndentationError: unexpected indent
退出 while循環(huán)
在某些情況下,使用break關鍵字退出 while循環(huán)。使用 if 條件確定何時退出 while循環(huán),如下所示。
Example: Breaking while loop
num = 0
while num < 5:
num += 1 # num += 1 is same as num = num + 1
print('num = ', num)
if num == 3: # condition before exiting a loop
break Output
num = 1
num = 2
num = 3
繼續(xù)下一次迭代
使用continue關鍵字開始下一次迭代,在某些條件下跳過continue語句之后的語句,如下所示。
Example: Continue in while loop
num = 0
while num < 5:
num += 1 # num += 1 is same as num = num + 1
if num > 3: # condition before exiting a loop
continue
print('num = ', num) Output
num = 1
num = 2
num = 3
同時用其他塊循環(huán)
else塊可以跟隨while循環(huán)。當while循環(huán)的布爾表達式計算為False時,將執(zhí)行 else 塊。
使用continue關鍵字開始下一次迭代,在某些條件下跳過continue語句之后的語句,如下所示。
Example: while loop with else block
num = 0
while num < 3:
num += 1 # num += 1 is same as num = num + 1
print('num = ', num)
else:
print('else block executed') Output
num = 1
num = 2
num = 3
else block executed 下面的 Python 程序連續(xù)地從用戶那里獲取一個數(shù)字作為輸入,并計算平均值,只要用戶輸入一個正數(shù)。這里,重復塊(循環(huán)的主體)要求用戶輸入一個數(shù)字,累計相加,如果不是負數(shù),則保持計數(shù)。
Example: while loop
num=0
count=0
sum=0
while num>=0:
num = int(input('enter any number .. -1 to exit: '))
if num >= 0:
count = count + 1 # this counts number of inputs
sum = sum + num # this adds input number cumulatively.
avg = sum/count
print('Total numbers: ', count, ', Average: ', avg) 當用戶提供負數(shù)時,循環(huán)終止并顯示到目前為止提供的數(shù)字的平均值。下面是上述代碼的運行示例:
Output
enter any number .. -1 to exit: 10
enter any number .. -1 to exit: 20
enter any number .. -1 to exit: 30
enter any number .. -1 to exit: -1
Total numbers: 3, Average: 20.0 網(wǎng)頁標題:Pythonwhile循環(huán)
URL網(wǎng)址:http://www.5511xx.com/article/cciddgi.html


咨詢
建站咨詢
