for 循环

Python for Developers 入门

Jasmin Ludolf

Senior Data Science Content Developer

单个比较

# 配料数量
quantities = [500, 400, 15, 20, 30, 5]
# 验证数值
quantities[0] < 10
False
quantities[1] < 10
False
Python for Developers 入门

for 循环语法

for value in sequence:
    action
  • sequence 中的每个 value 执行 action

    • 由于上一行的冒号,action 需缩进
  • sequence = 可迭代对象,如列表、字典等

  • value = 迭代变量,即索引
    • 占位名(可任意命名),常用 i
Python for Developers 入门

打印单个值

# 配料列表
ingredients = ["pasta", "tomatoes", "garlic", "basil", "olive oil", "salt"]


# 遍历并打印每个配料 for ingredient in ingredients:
print(ingredient)
pasta
tomatoes
garlic
basil
olive oil
salt
Python for Developers 入门

for 循环中的条件语句

quantities = [1000, 800, 40, 30, 30, 15]

for qty in quantities:
Python for Developers 入门

for 循环中的条件语句

quantities = [1000, 800, 40, 30, 30, 15]

for qty in quantities:

# 检查数量是否大于 500 if qty > 500: print("库存充足") elif qty >= 100: print("小份够用") else: print("快用完了!")
Python for Developers 入门

for 循环中的条件语句

库存充足
小份够用
快用完了!
快用完了!
快用完了!
Python for Developers 入门

遍历字符串

ingredient_name = "pasta"

# 遍历每个字符 for letter in ingredient_name: print(letter)
p
a
s
t
a
  • 适用于验证文本、检查特殊字符
Python for Developers 入门

遍历字典

ingredients = {"pasta": 500, "tomatoes": 400, "garlic": 30}

# 同时遍历键和值 for item, qty in ingredients.items(): print(item, ":", qty, "grams")
pasta : 500 grams
tomatoes : 400 grams
garlic : 30 grams
  • item = 键(配料名)
  • qty = 值(数量)
Python for Developers 入门

遍历字典

ingredients = {"pasta": 500, "tomatoes": 400, "garlic": 30}
factor = 2

# 计算缩放后的数量 for item, qty in ingredients.items(): scaled_qty = qty * factor print(item, ":", scaled_qty, "grams")
pasta : 1000 grams
tomatoes : 800 grams
garlic : 60 grams
Python for Developers 入门

遍历字典

# 仅遍历键
for item in ingredients.keys():
    print(item)
pasta
tomatoes
garlic
# 仅遍历值
for qty in ingredients.values():
    print(qty, "grams")
500 grams
400 grams
30 grams
Python for Developers 入门

range

range(start, end + 1)
  • start = 起始数
  • end = 结束数
  • 用于生成或修改数值
for i in range(1, 6):
    print(i)
1
2
3
4
5
Python for Developers 入门

让我们来练习!

Python for Developers 入门

Preparing Video For Download...