Python循环
for循环
foods = ['黄焖鸡', '麻婆豆腐', '鱼香肉丝']
for food in foods:
print(food)
输出:
黄焖鸡
麻婆豆腐
鱼香肉丝
计算1-10的整数之和
sum = 0
for x in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:
sum = sum + x
print(sum)
输出:
55
range()
list(range(5))
输出:
[0, 1, 2, 3, 4]
while循环
只要条件满足,就不断循环,条件不足时退出循环。
sum = 0
n = 99
while n > 0:
sum = sum + n
n = n - 2
print(sum)
输出:
2500
break
break
语句可以提前退出循环
n = 1
while n <= 100:
if n > 10: # 当n = 11时,条件满足,执行break语句
break # break语句会结束当前循环
print(n)
n = n + 1
print('END')
continue
continue
跳过这次循环,直接开始下一次循环。
n = 0
while n < 10:
n = n + 1
if n % 2 == 0: # 如果n是偶数,执行continue语句
continue # continue语句会直接继续下一轮循环,后续的print()语句不会执行
print(n)