Book a free demo

Confident ยท ages 11+ ยท dictionaries ยท loops ยท formatting

Shopping basket in Python.

Add up the price of items in a basket, with quantities and a discount.

The program

Press Run to see what it prints. Change anything you like, then run it again.

prices = {"apple": 30, "bread": 45, "milk": 28, "rice": 90}
basket = {"apple": 4, "milk": 2, "rice": 1}

total = 0
for item, quantity in basket.items():
    cost = prices[item] * quantity
    print(f"{item}: {quantity} x {prices[item]} = {cost}")
    total = total + cost

print("Total:", total)
if total > 200:
    discount = total * 10 // 100
    print("Discount:", discount)
    print("To pay:", total - discount)
apple: 4 x 30 = 120
milk: 2 x 28 = 56
rice: 1 x 90 = 90
Total: 266
Discount: 26
To pay: 240

How it works

  1. The dictionary prices gives the price of each item. basket says how many of each.
  2. .items() goes through the dictionary giving each key and its value.
  3. The discount only applies if the total is over 200, so it sits inside an if.
See the Python path โ†’

Try this

  • Add more items to the shop and basket.
  • Give a different discount for different totals.
  • Print the items from the most expensive to the cheapest.

Stuck on an error? Read how to debug Python.

Similar ideas

More programs

All programs โ†’

FAQ

Shopping basket: questions

What does the shopping basket program do?

Add up the price of items in a basket, with quantities and a discount. It prints: apple: 4 x 30 = 120 / milk: 2 x 28 = 56 / rice: 1 x 90 = 90 โ€ฆ

Which Python ideas does it use?

dictionaries, loops, formatting. Confident level, suitable from about age 11.

How do I run it?

Press Run on this page. To run it on your own computer, install Python 3 and save the code in a file ending in .py. It prints the same thing.

What should I try next?

Add more items to the shop and basket. Give a different discount for different totals. Print the items from the most expensive to the cheapest.

Start a conversation

Want a teacher to guide the learning?

Tell us the learner's age and what they can already do, and we will suggest a starting point. A parent or guardian can make the enquiry.

  • Tell us the learnerโ€™s age or grade and goals
  • Weโ€™ll suggest a suitable class or learning path
  • Weโ€™ll confirm format, timing and fees with a parent or guardian

For a childโ€™s class, please have a parent or guardian send the enquiry. Avoid sharing passwords or sensitive personal details.

Weโ€™ll use your details only to respond to this request.

Play it, don't just read it

Write some code right now

Free games that need no sign-up. Pick one and play for five minutes.

All free games โ†’
Chat on WhatsApp
Esc

Try