Python 中 for in / while / break / continue (循环控制)

水深无声 2022-05-30 12:25 267阅读 0赞

for in

for 变量 in [ 列表或元组 ]
将in后的每个元素代入到变量中、

例:

  1. sum = 0
  2. for x in range(21):
  3. sum = sum + x
  4. print(sum)
  5. -----------------------------
  6. 210
  7. Process finished with exit code 0

range()函数、可以生成一个整数序列、再通过list()函数可以转换为list、

函数语法
range(start, stop[, step])
参数说明:
start: 计数从 start 开始。默认是从 0 开始。例如range(5)等价于range(0, 5);
stop: 计数到 stop 结束,但不包括 stop。例如:range(0, 5) 是[0, 1, 2, 3, 4]没有5
step:步长,默认为1。例如:range(0, 5) 等价于 range(0, 5, 1)


while

条件满足、不断循环、 条件不足时、退出循环、

例:

  1. L = ['Bart', 'Lisa', 'Adam']
  2. n=0
  3. while n<3:
  4. print('helllo,%s !'% (L[n]))
  5. n=n+1
  6. --------------------------------------------
  7. helllo,Bart
  8. helllo,Lisa
  9. helllo,Adam
  10. Process finished with exit code 0

break

提前退出循环

例:

  1. n = 1
  2. while n <= 10:
  3. if n > 2:
  4. break
  5. print(n)
  6. n = n + 1
  7. print('END')
  8. --------------------------------------
  9. 1
  10. 2
  11. END
  12. Process finished with exit code 0

continue

跳过当前循环块中的剩余语句,然后继续进行下一轮循环。
例:

  1. n = 0
  2. while n < 10:
  3. n = n + 1
  4. if n % 2 == 0:
  5. continue
  6. print(n)
  7. -----------------------------------
  8. 1
  9. 3
  10. 5
  11. 7
  12. 9
  13. Process finished with exit code 0

发表评论

表情:
评论列表 (有 0 条评论,267人围观)

还没有评论,来说两句吧...

相关阅读