Python while 循环
Python while 循环
循环在编程中用于重复特定的代码块。在本文中,您将学习在 Python 中创建 while 循环。
视频:Python while 循环
Python 中的 while 循环是什么?
Python中的while循环用于迭代一段代码,只要测试表达式(条件)为真。
我们一般在事先不知道迭代次数的情况下使用这个循环。
Python中while循环的语法
while test_expression: Body of while
在 while 循环中,首先检查测试表达式。只有当 test_expression
计算结果为 True
.一次迭代后,再次检查测试表达式。这个过程一直持续到 test_expression
计算结果为 False
.
在 Python 中,while 循环的主体是通过缩进确定的。
正文以缩进开始,第一条未缩进的行标记结束。
Python 将任何非零值解释为 True
. None
和 0
被解释为 False
.
while循环的流程图
<图>示例:Python while 循环
# Program to add natural
# numbers up to
# sum = 1+2+3+...+n
# To take input from the user,
# n = int(input("Enter n: "))
n = 10
# initialize sum and counter
sum = 0
i = 1
while i <= n:
sum = sum + i
i = i+1 # update counter
# print the sum
print("The sum is", sum)
当你运行程序时,输出将是:
Enter n: 10 The sum is 55
在上面的程序中,测试表达式将是 True
只要我们的计数器变量 i 小于或等于 n (我们的程序中有 10 个)。
我们需要增加循环体中计数器变量的值。这非常重要(而且大多被遗忘)。否则将导致无限循环(永无止境的循环)。
最后显示结果。
While 与 else 循环
与 for 循环相同,while 循环也可以有一个可选的 else
块。
else
如果 while 循环中的条件计算结果为 False
,则执行部分 .
while 循环可以用 break 语句终止。在这种情况下,else
部分被忽略。因此,while 循环的 else
如果没有发生中断并且条件为假,则部分运行。
这里有一个例子来说明这一点。
'''Example to illustrate
the use of else statement
with the while loop'''
counter = 0
while counter < 3:
print("Inside loop")
counter = counter + 1
else:
print("Inside else")
输出
Inside loop Inside loop Inside loop Inside else
在这里,我们使用一个计数器变量来打印字符串 Inside loop 三遍。
在第四次迭代中,while
中的条件 变成 False
.因此,else
部分被执行。
Python