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循环的流程图
示例: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
在上述程序中,只要我们的计数器变量i小于或等于n(在我们的程序中为 10),则测试表达式为True。
我们需要在循环体内增加计数器变量的值。 这是非常重要的(并且几乎被遗忘了)。 否则,将导致无限循环(永无止境的循环)。
最后,显示结果。
While循环与else
与for循环相同,while循环也可以具有可选的else块。
如果while循环中的条件求值为False,则执行else部分。
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
在这里,我们使用计数器变量将字符串内部循环打印三遍。
在第四次迭代中,while中的条件变为False。 因此,执行else部分。