🐍 前端开发 0 基础学 Python 入门指南:循环篇
从 JavaScript 到 Python,掌握循环的艺术!深入理解 while 和 for 循环的使用技巧。
📝 一、for 循环:优雅的迭代
1.1 基本 for 循环
Python 的 for 循环更像 JavaScript 的 for...of,专注于遍历序列元素:
# 遍历列表
fruits = ["苹果", "香蕉", "橙子"]
for fruit in fruits:
print(f"我喜欢吃{fruit}")
# 输出:
# 我喜欢吃苹果
# 我喜欢吃香蕉
# 我喜欢吃橙子
# 遍历字符串
for char in "Python":
print(char)
# 输出: P y t h o n (每个字符一行)
# 遍历字典
user = {"name": "张三", "age": 25, "city": "北京"}
for key in user:
print(f"{key}: {user[key]}")
1.2 使用 range() 函数
range() 是 Python 循环中的利器,用于生成数字序列:
# range(stop) - 从 0 到 stop-1
for i in range(5):
print(i) # 输出: 0 1 2 3 4
# range(start, stop) - 从 start 到 stop-1
for i in range(1, 6):
print(i) # 输出: 1 2 3 4 5
# range(start, stop, step) - 指定步长
for i in range(0, 10, 2):
print(i) # 输出: 0 2 4 6 8
# 倒序循环
for i in range(10, 0, -1):
print(i) # 输出: 10 9 8 7 6 5 4 3 2 1
1.3 enumerate() - 获取索引和值
需要同时获取索引和值?使用 enumerate():
fruits = ["苹果", "香蕉", "橙子"]
# 传统方式(不推荐)
for i in range(len(fruits)):
print(f"{i}: {fruits[i]}")
# ✅ 推荐方式:使用 enumerate()
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
# 可以指定起始索引
for index, fruit in enumerate(fruits, start=1):
print(f"第{index}个水果: {fruit}")
# 输出:
# 第1个水果: 苹果
# 第2个水果: 香蕉
# 第3个水果: 橙子
1.4 对比 JavaScript
| Python | JavaScript | 说明 |
|---|---|---|
for item in list: | for (let item of list) | 遍历元素 |
for i in range(5): | for (let i=0; i<5; i++) | 数字循环 |
for i, v in enumerate(list): | list.forEach((v, i) => {}) | 索引+值 |
for key in dict: | for (let key in obj) | 遍历键 |
🔄 二、while 循环:条件驱动
2.1 基本 while 循环
当不知道循环次数,只知道循环条件时,使用 while:
# 基本 while 循环
count = 0
while count < 5:
print(f"当前计数: {count}")
count += 1
# 用户输入验证
password = ""
while password != "123456":
password = input("请输入密码: ")
if password != "123456":
print("密码错误,请重试!")
print("密码正确!")
2.2 无限循环
# ⚠️ 小心无限循环!确保有退出条件
while True:
command = input("输入命令 (quit 退出): ")
if command == "quit":
break
print(f"执行命令: {command}")
# 游戏主循环
game_running = True
while game_running:
# 游戏逻辑
user_input = input("继续游戏? (y/n): ")
if user_input == "n":
game_running = False
2.3 while vs for
# ✅ 适合用 for:已知循环次数
for i in range(10):
print(i)
# ✅ 适合用 while:未知循环次数,条件驱动
num = 1
while num < 1000:
num *= 2
print(f"第一个大于1000的2的幂: {num}")
# ✅ 适合用 while:需要复杂的退出条件
attempts = 0
success = False
while attempts < 3 and not success:
# 尝试某个操作
attempts += 1
🎯 三、循环控制语句
3.1 break - 跳出循环
break 用于完全终止循环:
# 查找第一个偶数
numbers = [1, 3, 5, 8, 9, 10]
for num in numbers:
if num % 2 == 0:
print(f"找到第一个偶数: {num}")
break # 找到后立即退出
# 在 while 中使用 break
count = 0
while True:
count += 1
if count > 5:
break
print(count)
3.2 continue - 跳过本次循环
continue 跳过当前迭代,继续下一次:
# 只打印奇数
for i in range(10):
if i % 2 == 0:
continue # 跳过偶数
print(i) # 只会打印 1, 3, 5, 7, 9
# 跳过空字符串
words = ["hello", "", "world", "", "python"]
for word in words:
if not word:
continue
print(word.upper())
3.3 else - 循环的 else 子句
🌟 Python 特色:循环可以有 else 子句!
# for...else:循环正常结束时执行
numbers = [1, 3, 5, 7, 9]
for num in numbers:
if num % 2 == 0:
print("找到偶数")
break
else:
# 如果循环正常结束(没有 break)才执行
print("没有找到偶数")
# while...else
count = 0
while count < 5:
print(count)
count += 1
else:
print("循环正常结束") # 会执行
# 被 break 中断时,else 不执行
count = 0
while count < 10:
if count == 3:
break
count += 1
else:
print("这句不会执行") # 不会执行
3.4 pass - 占位符
pass 是一个空操作,用于占位:
# 暂时不实现的循环
for i in range(10):
pass # 什么都不做
# 配合条件使用
for num in numbers:
if num < 0:
pass # 暂时忽略负数
else:
print(num)
💡 四、进阶技巧
4.1 列表推导式(List Comprehension)
用一行代码替代简单的 for 循环:
# 传统方式
squares = []
for i in range(10):
squares.append(i ** 2)
# ✅ 列表推导式(更 Pythonic)
squares = [i ** 2 for i in range(10)]
print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# 带条件的列表推导式
even_squares = [i ** 2 for i in range(10) if i % 2 == 0]
print(even_squares) # [0, 4, 16, 36, 64]
# 字符串处理
words = ["hello", "world", "python"]
upper_words = [word.upper() for word in words]
print(upper_words) # ['HELLO', 'WORLD', 'PYTHON']
4.2 嵌套循环
# 打印乘法表
for i in range(1, 10):
for j in range(1, i + 1):
print(f"{j}×{i}={i*j}", end="\t")
print() # 换行
# 二维列表遍历
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
for row in matrix:
for num in row:
print(num, end=" ")
print()
# 使用 break 只能跳出当前层循环
for i in range(3):
for j in range(3):
if j == 1:
break # 只跳出内层循环
print(f"i={i}, j={j}")
🎮 五、实战案例
5.1 案例 1:猜数字游戏
import random
# 生成1-100的随机数
secret_number = random.randint(1, 100)
attempts = 0
max_attempts = 7
print("🎮 猜数字游戏开始!我想了一个1-100之间的数字。")
while attempts < max_attempts:
guess = int(input(f"第{attempts + 1}次尝试,请输入你的猜测: "))
attempts += 1
if guess == secret_number:
print(f"🎉 恭喜你猜对了!用了{attempts}次尝试。")
break
elif guess < secret_number:
print("📈 太小了,再试试更大的数字!")
else:
print("📉 太大了,再试试更小的数字!")
else:
print(f"😢 很遗憾,次数用完了!答案是{secret_number}")
5.2 案例 2:购物车统计
# 购物车商品列表
shopping_cart = [
{"name": "笔记本", "price": 5999, "quantity": 1},
{"name": "鼠标", "price": 99, "quantity": 2},
{"name": "键盘", "price": 299, "quantity": 1},
{"name": "显示器", "price": 1999, "quantity": 1}
]
print("🛒 购物车清单:")
print("-" * 50)
total = 0
for index, item in enumerate(shopping_cart, start=1):
subtotal = item["price"] * item["quantity"]
total += subtotal
print(f"{index}. {item['name']:<10} "
f"单价: ¥{item['price']:<6} "
f"数量: {item['quantity']:<3} "
f"小计: ¥{subtotal}")
print("-" * 50)
print(f"总计: ¥{total}")
# 输出:
# 🛒 购物车清单:
# --------------------------------------------------
# 1. 笔记本 单价: ¥5999 数量: 1 小计: ¥5999
# 2. 鼠标 单价: ¥99 数量: 2 小计: ¥198
# 3. 键盘 单价: ¥299 数量: 1 小计: ¥299
# 4. 显示器 单价: ¥1999 数量: 1 小计: ¥1999
# --------------------------------------------------
# 总计: ¥8495
5.3 案例 3:数据清洗
# 清洗用户输入的邮箱列表
emails = [
" zhang@example.com ",
"",
"INVALID",
"li@test.com",
" ",
"wang@company.org ",
"not-an-email"
]
valid_emails = []
for email in emails:
# 去除空白
cleaned = email.strip()
# 跳过空字符串
if not cleaned:
continue
# 验证邮箱格式(简单验证)
if "@" not in cleaned or "." not in cleaned:
print(f"❌ 跳过无效邮箱: {cleaned}")
continue
# 转换为小写并添加到结果
valid_emails.append(cleaned.lower())
print(f"✅ 有效邮箱: {cleaned.lower()}")
print(f"\n共收集到 {len(valid_emails)} 个有效邮箱")
5.4 案例 4:九九乘法表
# 完整版九九乘法表
print("九九乘法表")
print("=" * 70)
for i in range(1, 10):
for j in range(1, i + 1):
print(f"{j}×{i}={i*j:2}", end=" ")
print()
# 输出:
# 九九乘法表
# ======================================================================
# 1×1= 1
# 1×2= 2 2×2= 4
# 1×3= 3 2×3= 6 3×3= 9
# ...
📊 六、性能对比
6.1 for vs while 性能
import time
# 测试 for 循环
start = time.time()
total = 0
for i in range(1000000):
total += i
end = time.time()
print(f"for 循环耗时: {end - start:.4f}秒")
# 测试 while 循环
start = time.time()
total = 0
i = 0
while i < 1000000:
total += i
i += 1
end = time.time()
print(f"while 循环耗时: {end - start:.4f}秒")
# ✅ for 循环通常更快,因为它在 C 层面优化
6.2 列表推导式 vs 普通循环
import time
# 普通循环
start = time.time()
squares = []
for i in range(100000):
squares.append(i ** 2)
end = time.time()
print(f"普通循环: {end - start:.4f}秒")
# 列表推导式
start = time.time()
squares = [i ** 2 for i in range(100000)]
end = time.time()
print(f"列表推导式: {end - start:.4f}秒")
# ✅ 列表推导式通常更快,且代码更简洁
⚠️ 七、常见陷阱
7.1 修改正在遍历的列表
# ❌ 错误:在遍历时修改列表
numbers = [1, 2, 3, 4, 5]
for num in numbers:
if num % 2 == 0:
numbers.remove(num) # 危险!会跳过元素
print(numbers) # [1, 3, 5] 看似正确,但可能出错
# ✅ 正确方法1:遍历副本
numbers = [1, 2, 3, 4, 5]
for num in numbers[:]: # numbers[:] 创建副本
if num % 2 == 0:
numbers.remove(num)
# ✅ 正确方法2:使用列表推导式
numbers = [1, 2, 3, 4, 5]
numbers = [num for num in numbers if num % 2 != 0]
7.2 循环中的变量作用域
# Python 的循环变量会"泄露"到外部
for i in range(5):
pass
print(i) # 4 - 变量 i 仍然存在!
# JavaScript 的 let 不会泄露
# for (let i = 0; i < 5; i++) {}
# console.log(i); // ReferenceError
7.3 死循环
# ❌ 忘记更新循环变量
count = 0
while count < 5:
print(count)
# 忘记写 count += 1,造成死循环!
# ✅ 确保有退出条件
count = 0
while count < 5:
print(count)
count += 1
🎓 八、最佳实践
8.1 选择合适的循环
# ✅ 已知次数,用 for
for i in range(10):
print(i)
# ✅ 条件驱动,用 while
while user_wants_to_continue():
do_something()
# ✅ 遍历集合,用 for...in
for item in collection:
process(item)
8.2 使用 Pythonic 的写法
# ❌ 不推荐:C 风格的循环
i = 0
while i < len(items):
print(items[i])
i += 1
# ✅ 推荐:Python 风格
for item in items:
print(item)
# ❌ 不推荐:手动管理索引
for i in range(len(items)):
print(f"{i}: {items[i]}")
# ✅ 推荐:使用 enumerate
for i, item in enumerate(items):
print(f"{i}: {item}")
8.3 保持代码简洁
# ❌ 过于复杂
result = []
for item in items:
if condition(item):
transformed = transform(item)
result.append(transformed)
# ✅ 使用列表推导式
result = [transform(item) for item in items if condition(item)]
📚 九、总结对比
Python vs JavaScript 循环语法
| 功能 | Python | JavaScript |
|---|---|---|
| 遍历元素 | for item in list: | for (let item of list) |
| 遍历索引 | for i in range(n): | for (let i=0; i<n; i++) |
| 条件循环 | while condition: | while (condition) |
| 跳出循环 | break | break |
| 跳过迭代 | continue | continue |
| 循环 else | for...else: ✅ | ❌ 不支持 |
| 遍历键值对 | for k, v in dict.items(): | for (let [k, v] of Object.entries()) |
| 索引+值 | for i, v in enumerate(): | arr.forEach((v, i) => {}) |
🚀 十、练习题
练习 1:打印所有小于 100 的质数
# 你的代码
点击查看答案
print("小于100的质数:")
for num in range(2, 100):
is_prime = True
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
is_prime = False
break
if is_prime:
print(num, end=" ")
练习 2:实现简单的用户登录系统
提示:最多允许 3 次登录尝试
# 你的代码
点击查看答案
correct_username = "admin"
correct_password = "123456"
max_attempts = 3
for attempt in range(1, max_attempts + 1):
username = input("用户名: ")
password = input("密码: ")
if username == correct_username and password == correct_password:
print("✅ 登录成功!")
break
else:
remaining = max_attempts - attempt
if remaining > 0:
print(f"❌ 登录失败,还有{remaining}次机会")
else:
print("🔒 账号已锁定,请联系管理员")
🎉 总结
- for 循环:适合遍历序列和已知次数的循环
- while 循环:适合条件驱动和未知次数的循环
- break/continue:灵活控制循环流程
- else 子句:Python 独有特性,循环正常结束时执行
- 列表推导式:简洁优雅的 Pythonic 写法
- enumerate/zip:实用的遍历工具
掌握这些循环技巧,你就能写出更加优雅和高效的 Python 代码了!🐍✨