Something of Value- A day at the Supermarket


#1



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


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:
117.0

price: 1.5
stock: 32

price: 3
stock: 15

price: 4
stock: 6

price: 2
stock: 0
None


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. 
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.


#2

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.

Aside

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.


#3

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