Today you will
Store many products at once with lists and dictionaries, and use your Module 4 for loops to go through them.
- Store items in a list and look them up by position.
- Go through a list with a for loop, the same way as
range()in Module 4. - Add, change and remove items in a list.
- Store products and prices in a dictionary and look prices up by name.
- Use a dictionary and a list together to total an order.
Deep dive A: why do we need lists?
In Module 4 every variable held one value. But a shop has many products. Without a list, every item needs its own variable:
special1 = "Beef Patty"
special2 = "Coconut Tart"
special3 = "Sorrel Drink"
print(special1)
print(special2)
print(special3)Beef Patty
Coconut Tart
Sorrel DrinkNow add a fourth special, or forty. A list stores many values under one name: square brackets [ ], items separated by commas.
specials = ["Beef Patty", "Coconut Tart", "Sorrel Drink"]
print(specials)
print(len(specials), "specials today")['Beef Patty', 'Coconut Tart', 'Sorrel Drink']
3 specials todaylen() tells you how many items are in the list. It's the same len() you can use on text to count letters.#lets calculate the lenght of items or strings
name = input("enter all your names: ")
for i in name:
print(i.lower())
print(f"all of my names combined have {len(name)} letters in it") #using the len() built in functionenter all your names: Ann Lee
a
n
n
l
e
e
all of my names combined have 7 letters in itDeep dive B: positions (the index)
Every item in a list has a position, called its index. Python starts counting at 0, not 1.
| Index | Item | Counting from the end |
|---|---|---|
| 0 | Beef Patty | -3 |
| 1 | Coconut Tart | -2 |
| 2 | Sorrel Drink | -1 |
specials = ["Beef Patty", "Coconut Tart", "Sorrel Drink"]
print(specials[0]) # the first item
print(specials[1])
print(specials[-1]) # -1 is always the last itemBeef Patty
Coconut Tart
Sorrel DrinkAsk for a position that doesn't exist, and Python stops with an IndexError:
specials = ["Beef Patty", "Coconut Tart", "Sorrel Drink"]
print(specials[3])Traceback (most recent call last):
File "index_error.py", line 2, in <module>
print(specials[3])
~~~~~~~~^^^
IndexError: list index out of rangeDeep dive C: flashback - for loops on a list
In Module 4 you wrote for qty in range(1, 11): and for letter in "PATTY":. A for loop works exactly the same way on a list: it runs once for each item, in order, and the loop variable takes the next item each time.
| Loop | The variable takes... | Module |
|---|---|---|
for qty in range(1, 4): | 1, then 2, then 3 | 4 |
for letter in "PATTY": | P, A, T, T, Y | 4 |
for item in specials: | each product in the list | 5 |
specials = ["Beef Patty", "Coconut Tart", "Sorrel Drink"]
for item in specials:
print("Today:", item)
print("That's all the specials")Today: Beef Patty
Today: Coconut Tart
Today: Sorrel Drink
That's all the specialsThe running total from the Module 4 checkout works on a list too: start at 0 before the loop, add inside it.
prices = [5.00, 4.00, 3.50, 5.00]
total = 0
for price in prices:
total += price
print("Items:", len(prices))
print(f"Total: EC${total:.2f}")
print(f"Average: EC${total / len(prices):.2f}")Items: 4
Total: EC$17.50
Average: EC$4.38Python has shortcuts for the most common jobs: sum(), max() and min().
prices = [5.00, 4.00, 3.50, 5.00]
print("Total:", sum(prices))
print("Most expensive:", max(prices))
print("Cheapest:", min(prices))Total: 17.5
Most expensive: 5.0
Cheapest: 3.5collection = []
for i in range(5):
num = int(input(f"Enter number {i+1}: "))
collection.append(num)
print("The sum is:", sum(collection))
print("the highest # you entered was", max(collection))
print("the lowest # you entered was", min(collection))
print("the average was", sum(collection) / len(collection))
Enter number 1: 5
Enter number 2: 10
Enter number 3: 15
Enter number 4: 20
Enter number 5: 25
The sum is: 75
the highest # you entered was 25
the lowest # you entered was 5
the average was 15.0Deep dive D: changing a list
A list can change while the program runs. The dot means "do this to the list", just like .lower() on text in Module 3.
order.append(x)adds x to the endorder.remove(x)takes out the first x it findsorder[0] = xreplaces the item at position 0x in orderasks a True/False question: is x in the list?
order = ["Beef Patty", "Coconut Tart"]
order.append("Sorrel Drink") # customer adds a drink
print(order)
order[0] = "Cheese Patty" # swap the beef for cheese
print(order)
order.remove("Coconut Tart") # changed their mind
print(order)
print("Sorrel Drink" in order)
print("Coconut Tart" in order)['Beef Patty', 'Coconut Tart', 'Sorrel Drink']
['Cheese Patty', 'Coconut Tart', 'Sorrel Drink']
['Cheese Patty', 'Sorrel Drink']
True
FalseStart with an empty list [] and fill it inside a loop. This is the Module 4 checkout again, but now it remembers every price instead of forgetting it:
prices = []
while True:
entry = input("Item price (or 'done'): ")
if entry == "done":
break
prices.append(float(entry))
print("You bought", len(prices), "items:", prices)
print(f"Total: EC${sum(prices):.2f}")
print(f"Most expensive item: EC${max(prices):.2f}")Item price (or 'done'): 5
Item price (or 'done'): 4
Item price (or 'done'): 3.50
Item price (or 'done'): done
You bought 3 items: [5.0, 4.0, 3.5]
Total: EC$12.50
Most expensive item: EC$5.00Deep dive E: dictionaries - look things up by name
A list finds things by position. But at the till nobody asks "what's the price of item number 2?" They ask "how much is a coconut tart?"
A dictionary stores pairs: a key (the name) and a value (the price). Curly brackets { }, a colon between each key and its value, commas between pairs.
products = {"Beef Patty": 5.00, "Cheese Patty": 5.00, "Coconut Tart": 4.00}
print(products["Coconut Tart"])
print(len(products), "products")4.0
3 productsTo add a product or change a price, put the key in square brackets and use =. A new key adds a pair. A key that's already there gets its value replaced.
products = {"Beef Patty": 5.00, "Coconut Tart": 4.00}
products["Sorrel Drink"] = 3.50 # new key: adds a product
products["Beef Patty"] = 5.50 # existing key: changes the price
print(products){'Beef Patty': 5.5, 'Coconut Tart': 4.0, 'Sorrel Drink': 3.5}Keys must match exactly, like == in Module 3. A typo or different capitals gives a KeyError:
products = {"Beef Patty": 5.00, "Coconut Tart": 4.00}
print(products["coconut tart"])Traceback (most recent call last):
File "key_error.py", line 2, in <module>
print(products["coconut tart"])
~~~~~~~~^^^^^^^^^^^^^^^^
KeyError: 'coconut tart'So check first. in works on dictionaries too, and it checks the keys:
products = {"Beef Patty": 5.00, "Coconut Tart": 4.00}
#item = "Bread Pudding"
item = input("Enter Item To Search") #alternative way to search
if item in products:
print(item, "costs EC$", products[item])
else:
print("Sorry, we don't sell", item)Sorry, we don't sell Bread PuddingDeep dive F: looping through a dictionary
A for loop on a dictionary gives you each key. Add .items() and you get the key and the value together, so the loop has two variables separated by a comma.
products = {"Beef Patty": 5.00, "Cheese Patty": 5.00, "Coconut Tart": 4.00}
for name in products:
print(name)
print("-" * 22)
for name, price in products.items(): #.items is how we pull the product list
print(f"{name:<14} EC${price:5.2f}")
# Third loop: prints just the prices
#for price in products.values(): #products.values() is how we pull the price
#print(f"EC${price:5.2f}")Beef Patty
Cheese Patty
Coconut Tart
----------------------
Beef Patty EC$ 5.00
Cheese Patty EC$ 5.00
Coconut Tart EC$ 4.00Deep dive G: list or dictionary?
| Use | When | Shop example |
|---|---|---|
list [ ] | Order matters, or the same thing can appear more than once | The items on the counter: 2 beef patties appear twice |
dictionary { } | You look things up by a name | The price list, or stock count for each product |
Deep dive H: both together - a receipt
Real shop code uses both: the dictionary is the price list, the list is what this customer is buying. The loop goes through the order, looks up each price, and keeps a running total.
products = {"Beef Patty": 5.00, "Cheese Patty": 5.00, "Coconut Tart": 4.00, "Sorrel Drink": 3.50}
order = ["Beef Patty", "Beef Patty", "Sorrel Drink", "Coconut Tart"]
total = 0
for item in order:
price = products[item]
total += price
print(f"{item:<14} EC${price:5.2f}")
print("-" * 23)
print(f"{'TOTAL':<14} EC${total:5.2f}")Beef Patty EC$ 5.00
Beef Patty EC$ 5.00
Sorrel Drink EC$ 3.50
Coconut Tart EC$ 4.00
-----------------------
TOTAL EC$17.501. Lists and dictionaries
A list of specials and a dictionary of prices.
# Module 5 - lists and dictionaries
specials = ["Beef Patty", "Coconut Tart", "Sorrel Drink"] # a list
print("Today's specials:", specials[0], "and", len(specials) - 1, "more")
specials.append("Bread Pudding")
for item in specials:
print("-", item)
products = {"Beef Patty": 5.00, "Cheese Patty": 5.00, "Coconut Tart": 4.00} # a dictionary
print("A coconut tart costs EC$", products["Coconut Tart"])
products["Sorrel Drink"] = 3.50 # add a new product
for name, price in products.items():
print(f"{name:<14} EC${price:.2f}")Today's specials: Beef Patty and 2 more
- Beef Patty
- Coconut Tart
- Sorrel Drink
- Bread Pudding
A coconut tart costs EC$ 4.0
Beef Patty EC$5.00
Cheese Patty EC$5.00
Coconut Tart EC$4.00
Sorrel Drink EC$3.502. Take an order
The menu is a dictionary, the order is a list, and the while loop from Module 4 keeps taking items until the customer types done.
# Module 5 - take an order: a dictionary for prices, a list for the order
products = {"Beef Patty": 5.00, "Cheese Patty": 5.00, "Coconut Tart": 4.00, "Sorrel Drink": 3.50}
order = []
print("MENU")
for name, price in products.items():
print(f" {name:<14} EC${price:5.2f}")
while True:
item = input("Add item (or 'done'): ")
if item == "done":
break
if item in products:
order.append(item)
print(" Added", item)
else:
print(" Sorry, we don't sell", item)
total = 0
for item in order:
total += products[item]
print(f"{len(order)} items. Total: EC${total:.2f}")MENU
Beef Patty EC$ 5.00
Cheese Patty EC$ 5.00
Coconut Tart EC$ 4.00
Sorrel Drink EC$ 3.50
Add item (or 'done'): Beef Patty
Added Beef Patty
Add item (or 'done'): Sorrel Drink
Added Sorrel Drink
Add item (or 'done'): Pizza
Sorry, we don't sell Pizza
Add item (or 'done'): Beef Patty
Added Beef Patty
Add item (or 'done'): done
3 items. Total: EC$13.50print(f" {name:<14} EC${price:5.2f}") - Reminder that <14 reserves 14 character length for the name, and :5.2f reserves 5 character spaces for the price and .2f is for 2 decimal places in the currency format
Bug hunt
This program crashes, and it has 2 bugs. Read the last line of the error, fix that bug, run it again.
# BUG HUNT - this program crashes. There are 2 bugs.
# It should print all 3 specials, then the price of a coconut tart.
# 1. Run it. 2. Read the LAST line of the error. 3. Fix that one bug. 4. Repeat.
specials = ["Beef Patty", "Coconut Tart", "Sorrel Drink"]
for i in range(1, 4):
print(specials[i])
products = {"Beef Patty": 5.00, "Coconut Tart": 4.00}
print("A coconut tart costs EC$", products["Coconut tart"])Hints (open only if stuck)
- Where does a list start counting?
- How many positions does a 3-item list have, and what are they?
- Dictionary keys have to match exactly, capitals too.
Words to know
| Word | Meaning |
|---|---|
| List | Many values in order, in square brackets: ["Beef Patty", "Coconut Tart"] |
| Index | A position in a list, starting at 0: specials[0] |
len() | How many items are in a list (or letters in text) |
.append() | Adds an item to the end of a list |
.remove() | Takes an item out of a list |
in | Asks True/False: is it in the list (or a key in the dictionary)? |
| Dictionary | Pairs of key and value, in curly brackets: {"Beef Patty": 5.00} |
| Key / value | The name you look up / the answer you get back |
.items() | Gives each key and value together in a for loop |
Practice
Homework 5 (5%): price_list.py
A till for your own shop. It must:
Submit your .py file and a screenshot of it running, before the next module.
| Mark | Means |
|---|---|
| 5 | Runs and has everything |
| 3 | Runs with parts missing, or has errors |
| 1 | Started |
| 0 | Not submitted |
Quiz 5
Check yourself here, then take the graded quiz in the quiz section of robotics.a3tech.uk (two tries).
ADDITIONAL - STREAMLIT APP - SNEAK PEEK 5
Everything from today, plus Modules 3 and 4, as a web page. The menu is a dictionary, the customer picks items (Streamlit hands them back as a list), a for loop builds the receipt with a running total, and if / elif gives the party discount.
# order_app.py - lists, dictionaries, loops and if/elif in a Streamlit app
# Run it with: streamlit run order_app.py
import streamlit as st
st.title("Mama J's Bakery - Order Builder")
products = {"Beef Patty": 5.00, "Cheese Patty": 5.00, "Coconut Tart": 4.00,
"Sorrel Drink": 3.50, "Bread Pudding": 6.00} # Module 5: a dictionary
st.subheader("Menu")
for name, price in products.items(): # Module 5: .items()
st.write(f"{name}: EC${price:.2f}") # Module 4: f-strings
chosen = st.multiselect("What would you like?", list(products)) # gives back a LIST
total = 0 # Module 4: running total
items = 0
for name in chosen: # Module 4 + 5: for over a list
qty = st.number_input(f"How many {name}?", min_value=1, value=1, step=1, key=name)
line = products[name] * qty # Module 5: look up the price
total += line
items += qty
st.write(f"{qty} x {name} = EC${line:.2f}")
if items >= 12: # Module 3: if / elif / else
total = total * 0.85
st.success("Party order: 15% off!")
elif items >= 6:
total = total * 0.90
st.info("Big order: 10% off!")
elif items == 0:
st.warning("Pick something from the menu.")
st.subheader(f"Total: EC${total:.2f} for {items} items")See the browser. Pick Beef Patty and Sorrel Drink, then set them to 4 and 2:
4 x Beef Patty = EC$20.00
2 x Sorrel Drink = EC$7.00
Big order: 10% off!
Total: EC$24.30 for 6 items
Change Beef Patty to 10: Party order: 15% off! Total: EC$48.45 for 12 itemsYour mission today
Invent your own robot commands with functions, get answers back with return, and let the robot choose randomly.
Your own commands
Define them once at the top, then use them as many times as you like.
# Module 5 - Make your own commands (functions)
def forward(ms):
robot.set_motors(50, 50)
robot.wait(ms)
robot.stop()
def turn(direction):
if direction == "left":
robot.set_motors(-50, 50)
else:
robot.set_motors(50, -50)
robot.wait(400)
robot.stop()
forward(1000)
turn("left")
forward(1500)
turn("right")
forward(500)return and random
path_clear() answers True or False. The robot picks a random direction when it's blocked.
# Module 5 - Functions that give back an answer (return), and random choices
import random
def path_clear():
return robot.get_sensor(0) > 20 # True if the wall in front is far away
def random_turn():
direction = random.choice(["left", "right"])
print("Turning", direction)
if direction == "left":
robot.set_motors(-50, 50)
else:
robot.set_motors(50, -50)
robot.wait(400)
robot.stop()
for move in range(10):
if path_clear():
robot.set_motors(50, 50)
robot.wait(300)
else:
random_turn()
robot.stop()Robot words
| Code | What it means |
|---|---|
| Function | Your own command: def forward(ms): |
| Parameter | Information the command needs, in the brackets |
| Call | Using the command: forward(1000) |
return | Gives an answer back |
random.choice() | Picks one item at random |
Challenges
Try one at a time. Change the code, run it, and watch.
Build puzzle
Turn this repeated code into one function, then call it twice.
robot.set_motors(50, 50)
robot.wait(1000)
robot.stop()
robot.set_motors(50, 50)
robot.wait(1000)
robot.stop()Show the answer
def forward(ms):
robot.set_motors(50, 50)
robot.wait(ms)
robot.stop()
forward(1000)
forward(1000)Challenge puzzle
What does this print?
def double(n):
return n * 2
print(double(5))Show the answer
10Quiz 5
Pass with 3 out of 5. Then take it for points in the quiz section of robotics.a3tech.uk.