Python中的基本语句,包括条件语句和循环。
循环语句允许我们执行一个代码块多次。Python主要有两种类型的循环:for循环和while循环。
for 循环
定义:像「按清单购物🛒」,明确知道要买多少东西。
比喻:你有一张购物清单,依次处理每个商品。
count = 1
while count <= 5:
print(count)
count += 1
for i in range(1,6):
print(i)
1 2 3 4 5 1 2 3 4 5
# 示例1:遍历购物清单
shopping_list = ["苹果", "牛奶", "面包"]
for i in shopping_list: # 从清单逐个拿商品
print(f"购买了:{i}") # 打印购买动作
# 输出结果:
# 购买了:苹果
# 购买了:牛奶
# 购买了:面包
# 示例:打印0到9的数字
for i in range(10):
#for i in range(1,11):
print(i)
# 示例:使用while循环重复执行,直到条件不满足
count = 0
while count < 10:
print(count)
#count += 1
while 循环
定义:像「等待快递📦」,直到满足条件才停止。 比喻:不断刷新物流信息,直到显示“已签收”。
# 示例:输出 1 到 5
count = 1
while count <= 5:
print(count)
count += 1
# 示例2:等待快递签收
delivery_status = "运输中"
attempts = 0 # 记录刷新次数
while delivery_status != "已签收":
print("刷新中...")
attempts += 1
if attempts == 3: # 模拟第三次刷新成功
delivery_status = "已签收"
print("快递已签收!🎁")
for 循环与 while 循环的核心区别¶| 对比维度 | for 循环 |
while循环 |
|---|---|---|
| 适用场景 | 用于已知循环次数或明确范围的循环 | 用于不明确循环次数,满足条件才结束的循环 |
| 循环控制 | 自动遍历序列或范围 | 条件判断为False时停止 |
| 代码示例 | for i in range(5):print(i) |
count = 0while count < 5:print(count)count += 1 |
for循环,打印出列表[1, 2, 3, 4, 5]中的每个元素。¶for i in [1, 2, 3, 4, 5]:
print(i)
for i in range(1,6):
print(i)
a = [1,2,3,4,5]
for i in a:
print(i)
for i in range(1,6):
print(i)
任务:写一个「读书进度跟踪程序」,要求:
使用 for 循环遍历章节(1-10章)
到第5章时用 continue 跳过(假设这章太难)
到第8章时用 break 停止阅读
# 参考答案
for chapter in range(1, 11):
if chapter == 5:
#print("跳过第5章太难了!😰")
continue
if chapter == 8:
#print("累了,今天读到第8章吧~ 📖")
break
print(f"正在阅读第{chapter}章...")
课堂活动
1.问AI大模型
2.观看视频
# 示例:遇到 'banana' 就停止循环
fruits = ['apple', 'banana', 'cherry']
for i in fruits:
if i == 'banana':
break
print(i)
apple
# 示例:跳过 'banana'
fruits = ['apple', 'banana', 'cherry']
for i in fruits:
if i == 'banana':
continue
print(i)
apple cherry
for i in range(5):
print("_____")
if i == 3:
break #结束整个循环
print(i)
_____ 0 _____ 1 _____ 2 _____
for i in range(5):
print("_____")
if i == 3:
continue # 跳出当前循环,继续执行下一次循环
print(i)
_____ 0 _____ 1 _____ 2 _____ _____ 4
## 📝 练习题
请尝试完成以下编程练习。
### 练习1:使用 `for` 输出 1 到 10 的数字。
### 练习2:使用 `while` 计算 1+2+3+...+100 的总和。
### 练习3:使用 `for` 和 `continue` 打印 1 到 10 中的奇数。
### 练习4:使用 `while` 和 `break` 找出第一个能被 7 整除的大于 50 的数字。
for i in range(1,11):
print(i)
1 2 3 4 5 6 7 8 9 10
total = 0
for i in range(1,101):
total += i
print(total)
5050
sum_num = 0
i = 1
while i <= 100:
sum_num += i
i += 1
print(sum_num)
5050
for i in range