Making a Purchase(Please Help!)


#1

https://www.codecademy.com/courses/learn-python/lessons/a-day-at-the-supermarket/exercises/making-a-purchase?action=lesson_resume

The error message I got for this is:

Compute_bill([‘apple’]) returned 0 instead of 2



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


The correct code is:


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

So I’m wondering why these two produce different answers.

    total += prices[item]     <----correct
    prices[item] += total     <----incorrect


#2

of we remove the shorthand we get:

total = total + prices[item] <-- correct
prices[item] = prices[item] + total <-- incorrect

one updates total, the other update the value in dictionary belonging to key. (dictionaries have key value pairs, so this would for example increase the cost of an apple)


#3

Thank you for your help! It makes more sense once we remove the shorthand.
It looks like I have to go back and review incrementation.


#4

a+=b ------>a=a+b
you can use the second one instead of the first


#5

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