在 Python 中,我们使用 while 循环来重复执行一段代码,直到满足某个条件。例如,

number = 1

while number <= 3:

print(number)

number = number + 1

输出

1

2

3

在上面的例子中,我们使用 while 循环来打印从 1 到 3 的数字。只要条件 number <= 3 为 True,循环就会一直运行。

while 循环语法

while condition:

# body of while loop

这里,

while 循环评估 条件,它是一个布尔表达式。

如果条件为 True,则执行 while 循环的主体。然后再次评估条件。

这个过程会一直持续,直到条件为 False。

一旦条件评估为 False,循环就会终止。

提示: 我们应该在循环内部更新 条件 中使用的变量,使其最终评估为 False。否则,循环将持续运行,形成一个无限循环。

Python while 循环流程图

Python while 循环流程图

示例:Python while 循环

# Print numbers until the user enters 0

number = int(input('Enter a number: '))

# iterate until the user enters 0

while number != 0:

print(f'You entered {number}.')

number = int(input('Enter a number: '))

print('The end.')

输出

Enter a number: 3

You entered 3.

Enter a number: 1

You entered 1.

Enter a number: -4

You entered -4.

Enter a number: 0

The end.

上面程序的运行方式如下:

它要求用户输入一个数字。

如果用户输入非 0 的数字,则打印该数字。

如果用户输入 0,则循环终止。

无限 while 循环

如果 while 循环的条件始终评估为 True,则循环会持续运行,形成一个 无限 while 循环。例如,

age = 32

# The test condition is always True

while age > 18:

print('You can vote')

输出

You can vote

You can vote

You can vote

.

.

.

上述程序等同于

age = 32

# the test condition is always True

while True:

print('You can vote')

更多关于 Python while 循环带有 break 语句的 Python while 循环我们可以在 while 循环内部使用 break 语句 立即终止循环,而无需检查测试条件。例如,

while True:

user_input = input('Enter your name: ')

# terminate the loop when user enters end

if user_input == 'end':

print(f'The loop is ended')

break

print(f'Hi {user_input}')

输出

Enter your name: Kevin

Hi Kevin

Enter your name: end

The loop is ended

这里,while 循环的条件始终为 True。但是,如果用户输入 end,则由于 break 语句,循环会终止。

带有 else 子句的 Python while 循环在 Python 中,while 循环可以有一个可选的 else 子句,该子句在循环条件为 False 时执行。例如,counter = 0

while counter < 2:

print('This is inside loop')

counter = counter + 1

else:

print('This is inside else block')

输出

This is inside loop

This is inside loop

This is inside else block

这里,在第三次迭代时,counter 变为 2,这将终止循环。然后它执行 else 块并打印 This is inside else block。

注意:如果 while 循环被 break 语句终止,则 else 块将不会执行。

Python for 循环 vs while 循环for 循环 通常在已知迭代次数的情况下使用。例如,

# loop is iterated 4 times

for i in range(4):

print(i)

输出

0

1

2

3

当迭代次数未知时,通常使用 while 循环。例如,

while True:

user_input = input("Enter password: ")

# terminate the loop when user enters exit

if user_input == 'exit':

print(f'Status: Entry Rejected')

break

print(f'Status: Entry Allowed')

输出

Enter password: Python is Fun

Status: Entry Allowed

Enter password: exit

Status: Entry Rejected

另请阅读

Python if...else 语句

Copyright © 2088 2017乒乓球世界杯_世界杯体彩 - uzhiqu.com All Rights Reserved.
友情链接