Python while 循环

Jinku Hu 2023年1月30日 2018年2月11日
  1. while 循环示例
  2. while 循环结合 else
Python while 循环

在本节中,我们来介绍 while 循环,该循环内的语句会被执行多次,直到循环判断条件不为 True 为止。在一个 while 循环中,如果判断条件是 True,则执行 while 内部语句,这个过程一直持续到条件变为 False

whilefor 循环相比,主要使用在当你不知道将要执行多少次循环语句(迭代总数)时。

以下是 Python while 循环的语法:

while condition:
    block of statements

这里,如果 conditionTrue 的话,则控制进入主体 while 并执行内部语句块,当条件变为时 False,迭代将停止并且循环也会终止。

while 循环示例


sum = 0
i = 0			#initializing counter variable at 0
while i <= 10:		
    sum = sum + i
    i = i + 2			#incrementing counter variable with inter of 2 for even numbers
print("Sum of first five even numbers =", sum)
Sum of first five even numbers = 30

首先,需要初始化计数器变量的值 i,然后 while 的判断条件是如果 i 大于 10 则应该终止 while 循环。然后 i 在每次迭代中递增 2 来增加计数器变量,这将生成偶数序列,因为最初 i 为零。

i 变为 12 时,循环终止并将 sum 打印出来。在循环的每次迭代中,将值 i 累加到 sum

while 循环结合 else

while 循环语法中,你也可以在后面添加 else 语句块,改语句块在条件判断为 False 并且循环没有被跳出情况下被执行。

如果你使用 break 终止 while 循环,那它将忽略该 else 部分。
count = 0
while count < 4:
    print("You are inside while loop")
    count = count + 1
    print("You are in else part")
You are inside while loop
You are inside while loop
You are inside while loop
You are inside while loop
You are in else part

count 大于 4 时,else 部分会被执行。

Author: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

Founder of Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.


相关文章 - Python Loop