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
for value in sequence:
action
对 sequence 中的每个 value 执行 action
action 需缩进sequence = 可迭代对象,如列表、字典等
value = 迭代变量,即索引i# 配料列表 ingredients = ["pasta", "tomatoes", "garlic", "basil", "olive oil", "salt"]# 遍历并打印每个配料 for ingredient in ingredients:print(ingredient)
pasta
tomatoes
garlic
basil
olive oil
salt
quantities = [1000, 800, 40, 30, 30, 15]
for qty in quantities:
quantities = [1000, 800, 40, 30, 30, 15] for qty in quantities:# 检查数量是否大于 500 if qty > 500: print("库存充足") elif qty >= 100: print("小份够用") else: print("快用完了!")
库存充足
小份够用
快用完了!
快用完了!
快用完了!
ingredient_name = "pasta"# 遍历每个字符 for letter in ingredient_name: print(letter)
p
a
s
t
a
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 = 值(数量)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
# 仅遍历键
for item in ingredients.keys():
print(item)
pasta
tomatoes
garlic
# 仅遍历值
for qty in ingredients.values():
print(qty, "grams")
500 grams
400 grams
30 grams
range(start, end + 1)
start = 起始数end = 结束数for i in range(1, 6):
print(i)
1
2
3
4
5
Python for Developers 入门