Python教程-2.3节: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将任何非零值解释为TrueNone并且0被解释为False

While循环流程图

Python编程中的while循环
Python中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与其他循环

for循环相同,而while循环也可以具有可选else块。

else如果while循环中的条件求值为,则执行该部分False

while循环可以使用break语句终止。在这种情况下,该else零件将被忽略。因此,else如果没有中断并且条件为假,则while循环的一部分将运行。

这是一个示例来说明这一点。

'''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

在这里,我们使用计数器变量来打印字符串 内部循环 三次。

在第四次迭代中,条件in while变为False。因此,该else部分被执行。

0