1.1 for
循环语法
# 打印出1-20
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
for var in numbers:
print(var)
2.1 while
循环语法
while
循环:只要有条件满足,就会一直执行一组语句。Python中,while
表示信息是当……的时候,发生当while
循环的条件满足时,就会一直执行满足条件的语句。
# 打印1-20
i = 0
while i < 20:
i += 1
print(i)
3、break
和continue
3.1 break
如果想提前结束整个循环,可以使用 break
语句
# 对 1 到 20 的数字求和,当和大于 100 时,便停止求和
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
count = 0
for var in numbers:
count += var
if count >= 100:
break
print("count = ", count)
3.2 continue
break
语句是结束整个循环,如果想提前结束本轮循环,可以使用 continue
# 对 20 以内的偶数求和
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
count = 0
for var in numbers:
# 奇数,除以2的余数不为0,也就是不能被2整除
if var % 2 != 0:
# 当数字为奇数时,退出本次循环
continue
count += var
print("count = ", count)