Something of Value


#1

I dont understand why the first code with the stantement "total = total + value" in the line 5 works ,and the second code with ''total = 0 + value" dindnt work if the total is zero anyway.

total = 0
for key in prices:
    value = prices[key] * stock[key] 
    print value
    total = total + value
    
print total

total = 0
for key in prices:
    value = prices[key] * stock[key] 
    print value
    total = 0 + value
    
print total

#2

We need the total to accumulate, hence we add the value then reassign the new amount to the variable.

There is a way to write this using a compound operator,

total += value

Furthermore, we could write it without using an intermediate step of assigning to a variable...

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

#3

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