Something of Value- A day at the Supermarket


I don't get it, sometimes this code works but then sometimes it gives this error message: Oops, try again. Your code looks a bit off. Check the Hint if you need help! Your code threw the following error: name 'total' is not defined. But then sometimes when I submit it gives me the 'Congratulations you finished this section!' and I get the correct answer for a total being 117.

Correct answer apparently:

price: 1.5
stock: 32

price: 3
stock: 15

price: 4
stock: 6

price: 2
stock: 0

By the way, I found out I then add total = 0 in from of total += stock[item] * price[item] and then erase it, the code magically works somehow.

Replace this line with your code. 
for item in prices:
    total += stock[item] * prices[item]
print total

I just need an explanation of whether my code is right or its the system playing mindgames.


When using a compound operator the variable must be defined in order for the operation to work. That means giving it an initial value. Since we're adding, we start with zero. This would be before the loop.


The same would apply to string concatenation.

text += "some more text"

will raise the exception,

NameError: name 'text' is not defined

text = ""
text += "some more text"

will define the string so it has a type and an initial value that can be concatenated.


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