How does python know you want to add up the numbers? Something of Value


#1

Something of Value.
total = 0
for number in prices :
total += prices[number]*stock[number]
Using this code how does python know that number means the numbers after the key, couldn't it just of easily tried to multiply the keys?

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 number in prices :
    total += prices[number]*stock[number]

print total

#2

Can you please rephrase your question


#3

I think since you have already "defined" key in the previous loop, python understands that "number" must mean the other int/float/string in prices or stock. Hope that helps.


#4

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