Python - A Day at SuperMarket - Something of value


#1

Hi Guys, below is my code

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

I do not understand why we need to create a new variable ‘total’ and set it to zero, we could create it inside for loop and set it to ‘prices[cost] * stock[cost]’.
My code gives the result :

orange
price: 1.5
stock: 32
orange
48.0
48.0
pear
45
93.0
banana
24
117.0
apple
0
117.0
pear
price: 3
stock: 15
orange
48.0
48.0
pear
45
93.0
banana
24
117.0
apple
0
117.0
banana
price: 4
stock: 6
orange
48.0
48.0
pear
45
93.0
banana
24
117.0
apple
0
117.0
apple
price: 2
stock: 0
orange
48.0
48.0
pear
45
93.0
banana
24
117.0
apple
0
117.0

Although I’m allowed to go to the next topic, I don’t know if my result is right. Please help.


#2

Variables (that accumulate) are never created inside a for loop when their values are important afterward.


#3

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