Making a Purchase


#1



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


Well, I don't actually understand why do we have to loop the food list. Like, why can't I just skip the loop thing and do this instead?
I have included the upper code which is the correct one that got me through(I assume) and also the lower one in which I was wondering why can't I do this instead.

#This is the one which I got it correctly
def compute_bill(food):
    total = 0
    for x in food:
        total += prices[x]
    return total    

#This is the one I am wondering why can't it be used for the same purpose
def compute_bill(food):
    total = 0
    total += prices[food]
    return total


#2

In first case youre looping over your list food parameter's items using iteration variable x thats used as key for prices , you pass the key to global variable prices and adds amount to total at each iteration.

In second case..
You're trying to add total with prices[food] , you're passing food (which is a list here) to prices dictionary,food is a list and It throws an error.

Few things to do..
Revising the previous taught concepts might help--

  • for loops ,
  • how loops iterates over dictionary and lists.

#3

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