My code works - I don't know why


#1

https://www.codecademy.com/courses/python-beginner-en-IZ9Ra/2/2?curriculum_id=4f89dab3d788890003000096

Okay, so I have this code. But I got it right only after I read the forum. Before, I shopping list (with underscore) in the function instead of food. After I changed it to food, the code works. Why? How does it know where to get the foods if not from the shopping list?

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 food:
        total += prices[item]
    return total


#2

def compute_bill(food) just tells it, that the method takes one argument. This argument will be called "food" while within the method. You could replace "food" with "somethingelse" in the method and it would still work.

This makes the method / function reusable.. you can give it any list that looks like shopping_list (but has different fruits in it) and it would still work.

Somewhere in the background the method is tested using compute_bill(shopping_list), but it is hidden in the CodeCademy-Code, so that might be confusing.


#3

thanks for clarifying! Helped a lot :slight_smile:


#4