11. making a purchase


The give codes work and that is great and all, can somebody please take a second to walk through WHY it works and what each line is doing in conjunction with the previous codes?

11 Making a Purchase

I'm learning just like you, but here is my understanding:

You are first telling Python you have a new function defined called compute_bill with the argument called food. Understand that it really doesn't matter what you call the defined function or argument. The stuff that matters is inside the function.

def compute_bill(food):

Next, you are setting a variable called total, you can call this variable whatevertheheck you want to call it. This is a container that you are setting to a value of zero, so myvariable=0. Or, in this case:


Now that you have a variable with the value 0 inside of the function, before the for loop, this allows the function to reset this variable to zero anytime the function is ran again. This way the variable isn't still saved as the sum of a previous run.

Now the For loop. We tell Python, For every item (item here is a placeholder, you can call it whatevertheheck you want), but For item in food, Python, I want you to take that item and add it it's value to the value of my variable that I originally set to zero. In this way. Then return total is simply to call that final value out of your variable "total" that the For loop has steadily been adding to for each "item" passed into the argument.

So, what we have is a shopping list of "items" that we feed into our function "compute_bill" where we reset the value of our "total" variable to zero, and Python iterates For (each) item in food: add that key from prices[item] to my variable "total" value. Then when you are done with each item in my shopping list, return the sum of that value.


total += prices[item]

is the same as this

total = total+prices[item]


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.