Python 学习笔记 - 循环 while

Python 循环 - while

Python 中有

  • for 循环
  • while 循环

如果条件符合,while 可以循环执行。

无限循环

# 打印 0 到 9
c = 0
while c < 10:
  print(c)
  c += 1 # 注意,每次循环需要增大 c,否则 循环无法终止

break 语句

可以使用 break 在符合某一条件时来停止循环:

c = 0
while c < 10:
  print(c)
  c += 1 # 注意,每次循环需要增大 c,否则 循环无法终止
  if c == 5: break # c 等于 5 时,终止循环

continue 语句

continue 语句可以终止当前迭代,调到下一个迭代继续执行:

c = 0
while c < 10:
  c += 1 # 注意,每次循环需要增大 c,否则 循环无法终止
  if c == 5: continue # c 等于 5 时,停止当前迭代,进入到下一个循环
  print(c)

while else 语句

while else 结构里,条件为 False 时执行 else 里的语句:

c = 0
while c < 10:
  print(c)
  c += 1 # 注意,每次循环需要增大 c,否则 循环无法终止
else:
  print('c 大于 9')

你可能感兴趣的:(Python 学习笔记 - 循环 while)