Why it work after i remove the line: total=0


#1



prices = {
    "banana" : 4,
    "apple"  : 2,
    "orange" : 1.5,
    "pear"   : 3,
}
stock = {
    "banana" : 6,
    "apple"  : 0,
    "orange" : 32,
    "pear"   : 15,
}
for x in prices:
    total=0
    y=stock[x]*prices[x]
    total+=y
    print total


Why it work after i remove the total=0
but the result is
48.0
93.0
117.0
117.0
None


#2

total shouldn't be defined in the loop, given then its gets assigned a value of zero each iteration of the loop, not remembering values added to it from earlier iterations

If you removed it completely, it should given an error


#3

So, should i put it before the loop
like this:
total=0
for x in prices:
y=stock[x]*prices[x]
total+=y
print total

but why it output the series of number rather than only one number


#4

because total is inside the loop? So each iteration after a product price is added to the total, the new total prints

if you only want to print the final price, print total outside the loop


#5

Thanks a lot, i find the solution.


#6

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