- 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)
当你运行程序时,输出将是:
输入 n:10 总和是 55
Python中的while循环是什么?
只要测试表达式(条件)为真,Python 中的 while 循环就用于迭代一段代码。
当我们事先不知道迭代的次数时,我们通常会使用这个循环。
Python 中 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)
当你运行程序时,输出将是:
输入 n:10 总和是 55
在上面的程序中,测试表达式将True与我们的计数器变量一样长一世 小于或等于 n (在我们的程序中有 10 个)。
我们需要增加循环体中计数器变量的值。这非常重要(而且大多被遗忘)。否则将导致无限循环(永无止境的循环)。
最后,显示结果。
while 循环与 else
与for loops相同,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”)
输出
内循环 内循环 内循环 在别处
在这里,我们使用一个计数器变量来打印字符串 内循环 三次。
在第四次迭代中,条件while变为False。因此,该else部分被执行。
下一个教程:[Python 中断并继续](https://www.yuque.com/aifanj/odpp1n/mznuts)