用字典進行迴圈
你的食譜縮放器已經有雛形了!你有一個名為 recipe 的字典,鍵是食材名稱,值是番茄羅勒義大利麵所需的克數。現在你需要把所有用量放大 2 倍,好在派對上招待更多賓客。你將透過迴圈走訪字典項目並計算放大量。
本練習屬於課程
Python 入門(開發者向)
練習說明
- 使用
for迴圈走訪recipe字典,並以ingredient和qty作為迭代變數。 - 在迴圈中建立名為
scaled_qty的變數,將原本的用量乘上 2 的縮放係數。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
recipe = {
"fusilli": 500,
"tomatoes": 400,
"basil": 20,
"garlic": 15,
"olive oil": 15,
"salt": 7
}
# Loop through the recipe dictionary items
for ____, ____ in recipe.____:
# Calculate the scaled quantity by multiplying by 2
scaled_qty = qty ____
print(ingredient, ":", scaled_qty, "g")