使用清單進行條件式迴圈
在你把番茄羅勒義大利麵的食譜放大準備宴會前,需要先檢視各食材的用量,了解你要處理的內容。食譜用量以公克為單位,儲存在名為 quantities 的清單中。作為建立食譜放大器的第一步,你會迴圈走過這些用量,並用條件判斷加以分類——但此時還不會進行放大。這能讓你在修改前先了解食材分布。
本練習屬於課程
Python 入門(開發者向)
練習說明
- 使用
qty作為迭代變數,迴圈走訪quantities清單中的每個用量。 - 在迴圈中加入條件判斷:若
qty大於或等於 400 公克,則印出'Large quantity'。 - 加入
elif判斷:若qty大於或等於 200 公克,則印出'Medium quantity'。 - 加入
else子句處理其餘所有用量,並印出'Small quantity'。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
quantities = [500, 400, 20, 15, 15, 7]
# Loop through each quantity in the recipe
for ____ in ____:
# Check if it's a large quantity (400g or more)
____ ____ >= 400:
print('Large quantity')
# Check if it's a medium quantity (200g or more)
____ qty >= ____:
print('Medium quantity')
# Otherwise it's a small quantity
____:
print('Small quantity')