Why is this returning Total instead of just Apples?


#1



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


So, I am at my wits end. The code seems to be summing the total cost of the shopping list properly, but it will not return the cost of just the apple.

Any help appreciated!


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


#2

here..you need to make changes to make this code work

for food in shopping_list:
        total = total + prices[food]

Can you give me reason why you use food as iteration variable and abruptly used shopping_list which is not defined inside the function


#3

I'm not sure I understand your question. I used food as my iteration variable because it seemed to be quite descriptive and usable as a variable name. If I change the name from "food" to "fruit" or anything else I run into the same problem. So I don't know that is where I am stuck.

But it seems you mean that I first must somehow define shopping_list within the function in order for this to work properly. I don't mean to sound dim, but since the list already exists and I am asking the function to loop through it, do I need to first define shopping_list? The total for shopping_list ends up correct (7.5 = 4 + 2 + 1.5), so I thought there was something wrong with the compute_bill(['apple']) portion.

I guess I'm wrong. Perhaps another nudge?


#4

Ah! I think I get it. I need to refer to food within the for statement.


#5

Okay answer this..

z = 2

def sum1(x):
    return 2 * x

def sum2(y):
    return 2 * y

def sum3(z):
    return 2 * z

do you think if I pass z's (2) value in first two functions it will not work but If I pass the value of z in 3rd function,It will work ?
Also are all these three functions have different working/functionality ?


#6

Yeah food is your list on which you have to loop over using some iteration variable!


#7

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