Night 19: The pet shop
คุณเรียนจบคืนนี้แล้วด้วย Python หรือรหัสเทียม และนับรวมในทั้งสองภาษา คุณสามารถฝึกอีกครั้งได้ตามต้องการ
Tonight: the pet shop
- Your pet goes shopping! The shop keeps its prices in a dictionary.
- You will learn one thing: how to loop over a dictionary.
Words for tonight
| Word | Meaning |
|---|---|
| price | how much something costs |
| shop | a place where you buy things |
| total | all the numbers added together |
Loop over the keys
- A
forloop over a dictionary gives you each key. - Use the key to find the value.
prices = {"apple": 2, "fish": 5, "rice": 1}
for item in prices:
print(item, "costs", prices[item])
Find one price fast
- No loop is needed to find one price. Ask with the key.
prices = {"apple": 2, "fish": 5, "rice": 1}
item = "fish"
if item in prices:
print(prices[item])
else:
print("Sold out")
Add up a basket
- The running total from night 7 works here too.
prices = {"apple": 2, "fish": 5, "rice": 1}
basket = ["apple", "fish", "apple"]
total = 0
for item in basket:
total = total + prices[item]
print("Total:", total)
item |
price | total |
|---|---|---|
| 0 | ||
| apple | 2 | 2 |
| fish | 5 | 7 |
| apple | 2 | 9 |
- Now go shopping with your pet!
ความยาก 2/5 · 140 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
The shop has prices = {"apple": 2, "fish": 5, "rice": 1}. Use a for loop to print each item and its price. The first line is apple 2.
คลิก Run เพื่อดูผลลัพธ์ที่นี่
ความยาก 2/5 · 140 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Read an item with input(). If the shop has it, print its price. If not, print Sold out.
คลิก Run เพื่อดูผลลัพธ์ที่นี่
ความยาก 3/5 · 200 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Your pet buys 3 items. Read 3 items with input(), one at a time. Add up their prices in total and print it. Every item is in the shop.
คลิก Run เพื่อดูผลลัพธ์ที่นี่
ความยาก 4/5 · 280 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Find the cheapest item with a loop. Keep its name in cheapest. Print it. The answer is rice.
คลิก Run เพื่อดูผลลัพธ์ที่นี่