for循环用于针对序列中的每个元素的一个代码块。
while循环是不断的运行,直到指定的条件不满足为止。
while 条件:
条件成立重复执行的代码1
条件成立重复执行的代码2
……..
i = 1
while i <= 5:
print(i)
i = i + 1
i = 1
while i <=100:
print(i)
i = i +1
x = 1
y = 0
while x <=100:
y = y +x
x = x+1
print("1 到 100 的累加和为:", y)
x = 2
y = 0
while x <=100:
y = y + x
x = x + 2
print("1 到 100 的偶数累加和为:", y)
break 终止循环
continue 退出本次循环,继续下一次循环
total_apples = 5
eat_count = 0
while eat_count < 4:
eat_count += 1
print("吃了第", eat_count, "个苹果")
print("吃饱了,不吃了")
total_apples = 5
eat_count = 0
while eat_count < total_apples:
eat_count += 1
if eat_count == 3:
print("第", eat_count, "个苹果有虫子,不吃了")
continue
print("吃了第", eat_count, "个苹果")
print("吃完了所有的苹果")