Help!


#1

I was working on 9th exercise (Something of value) and stucked @ Finally, outside your loop, print total.
I've tried everything but program not letting me to print the total cost for all products. Finally, i tried:
prices = {
"banana" : 4,
"apple" : 2,
"orange" : 1.5,
"pear" : 3
}
stock = {
"banana" : 6,
"apple" : 0,
"orange" : 32,
"pear" : 15
}
total=0
for key in prices:

print key
print "price: %s" % prices[key]
print "stock: %s" % stock[key]
p=prices[key]*stock[key]
print p
total=total+p

print total

and its worked. But I am confused now.....
Why total=0 declare before for loop and if we declare inside the loop why didn't work and how it can effect the program.


#2

Loops are meant to repeat the same instructions automatically for a fixed number of times.
By putting total = 0 inside it, you are basically telling the computer to make total to 0 everytime you do a loop (reset). And so, the numbers that you've added are lost unless it's the very last one.

for example:

n = [1, 2, 3, 4, 5]
for i in n: #for every item in n
    total = 0 #reset total to 0 every time you run the loop (5 times)
    total += i #add items to total
    #repeat until i becomes 5 (last item in n)

output:
>> 5 #only outputs the last item, 5

while

n = [1, 2, 3, 4, 5]
total = 0 #initiates the variable, total, to add the items to
for i in n: #for every item in n
    total += i #add items to total
    #repeat until i becomes 5 (last item in n)

output:
>> 15 #outputs the total = 1+2+3+4+5

#3

Thank you so much...............

Your Answer Help me a lot....

Such a great place where the coders/fellows like you help the noobs


#4

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