Python 使用while
和作為關鍵字來構成一個條件循環,通過這個循環重復執行一個語句塊,直到指定的布爾表達式為真。
以下是 while
循環語法。
Syntax:
while [boolean expression]:
statement1
statement2
...
statementN
Python 關鍵字 while 有一個條件表達式,后跟:
符號,以增加縮進開始一個塊。 該塊有要重復執行的語句。這樣的塊通常被稱為循環體。身體將繼續執行,直到情況評估為True
。如果結果是False
,程序將退出循環。 以下示例演示了 while
循環。
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 并打印出來以顯示數字序列,如上所示。
循環體中的所有語句必須以相同的縮進開始,否則會引發IndentationError
。
Example: Invalid Indentation
num =0
while num < 5:
num = num + 1
print('num = ', num)
Output
print('num = ', num)
^
IndentationError: unexpected indent
退出 while
循環
在某些情況下,使用break
關鍵字退出 while
循環。使用 if 條件確定何時退出 while
循環,如下所示。
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
繼續下一次迭代
使用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
同時用其他塊循環
else
塊可以跟隨while
循環。當while
循環的布爾表達式計算為False
時,將執行 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 程序連續地從用戶那里獲取一個數字作為輸入,并計算平均值,只要用戶輸入一個正數。這里,重復塊(循環的主體)要求用戶輸入一個數字,累計相加,如果不是負數,則保持計數。
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)
當用戶提供負數時,循環終止并顯示到目前為止提供的數字的平均值。下面是上述代碼的運行示例:
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