Explain this loop?


#1




I was just curious as to why if i replace ' stock[key] ' with ' stock[x] ' I get all the values iterated through price * the value ( 34 ) of the key "orange"
(output: 48.0 96 128 64)

Should it not return an error as ' x ' isn't even defined?

Thanks!


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]

print
print

for key in prices:
    print (prices[key] * stock[x])


#2

Lol...I think I may have my answer to my question...

Wondering if 'x' already was assigned to something earlier and the object memory wasn't cleared ?


#3

Yes, that is, in fact, what must have happened. It relates to how Codecademy manages objects in memory. You can reload the page to remove those objects from Codecademy's memory.


#4

Thanks for confirming :slight_smile:


#5