Making a purchase


The error is : Oops, try again. compute_bill(['apple']) returned 6 instead of 2

shopping_list = ["banana", "orange", "apple"]

stock = {
"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15

prices = {
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3

Write your code below!

def compute_bill(food):
total = 0
for item in shopping_list:
total = total + prices["apple"]
return total


We passed shopping_list to the function which is locally referred to as food

for item in food:

This is a key literal. All it adds is the price of 'apple' multiple times. Use the item variable



Quick question, my code works just fine after replacing

for item in shopping_list


for item in food

Why doesn't shopping_list work and food works?



shopping_list is a global variable that is not accessible from inside the function, except as a passed in reference. food is still the same physical list, but locally accessible.

To make a global object directly accessible in a function, we need to declare it as a global.

global shopping_list

However, passing it as an argument is cleaner, and more explicit, and it frees the function of a dependency.


24 posts were split to a new topic: Compute bill