[9. Something of Value] Why is this code correct? Redefining variables


#1



Hi! In my code I have two lines, one indented and within the loop and another with print command (full code further below):
[indent here] total = total + prices[key] * stock[key]
print total + prices[key] * stock[key]

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

The code seems to be working just fine, but I have no idea why it works. In the loop I redefined the variable "total" and added the multiplication of stock and prices. Then after the loop, I redefined the variable again, so the final "total" would in fact be:
total = total + prices[key] * stock[key] + prices[key] * stock[key]
and not this:
total = total + prices[key] * stock[key]

Should there have been an error message? Is it a "local" variable and perhaps its redefition does not count outside the loop? Also there is no loop like "for key in prices" for the expression ofter the print command. It is not indented. Why is it not a problem?
Any further reading recommendations or explanations are welcome <3


prices = {
    "banana" : 4,
    "apple"  : 2,
    "orange" : 1.5,
    "pear"   : 3,
}
stock = {
    "banana" : 6,
    "apple"  : 0,
    "orange" : 32,
    "pear"   : 15,
}

for key in prices:
    print key
    print "price: %s" % prices[key]
    print "stock: %s" % stock[key]
    
total = 0
for key in prices:
    print prices[key] * stock[key]
    total = total + prices[key] * stock[key]
print total + prices[key] * stock[key]


#2

woah woah, you don't need to do all this

 print prices[key] * stock[key]
 total = total + prices[key] * stock[key]
print total + prices[key] * stock[key]

Just write total += number in prices * number in stock.

then return the total outside of for loop.


#3

OK. Thanks. Then again, why does it work? :confused:


#4

Well, it works for 1. because you are print prices[key] * stock[key]

You don't have a += sign, but since you did declare total twice and then printed the full value of total, that's probably why it let you pass. Although you could of just went print total take the total out, and put +=, you would of still passed as well.

There are several solutions to this lesson.