Python 中 for in / while / break / continue (循环控制)
for in
for 变量 in [ 列表或元组 ]
将in后的每个元素代入到变量中、
例:
sum = 0
for x in range(21):
sum = sum + x
print(sum)
-----------------------------
210
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
条件满足、不断循环、 条件不足时、退出循环、
例:
L = ['Bart', 'Lisa', 'Adam']
n=0
while n<3:
print('helllo,%s !'% (L[n]))
n=n+1
--------------------------------------------
helllo,Bart !
helllo,Lisa !
helllo,Adam !
Process finished with exit code 0
break
提前退出循环
例:
n = 1
while n <= 10:
if n > 2:
break
print(n)
n = n + 1
print('END')
--------------------------------------
1
2
END
Process finished with exit code 0
continue
跳过当前循环块中的剩余语句,然后继续进行下一轮循环。
例:
n = 0
while n < 10:
n = n + 1
if n % 2 == 0:
continue
print(n)
-----------------------------------
1
3
5
7
9
Process finished with exit code 0
还没有评论,来说两句吧...