Something of Value


#1



https://www.codecademy.com/courses/python-beginner-en-IZ9Ra/1/4?curriculum_id=4f89dab3d788890003000096#


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

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

My question is,after I run the codes it prints out the total for 4 times,(48.0 ,93.0 ,117.0 ,117.0),I understand that it's because of the loop thing,But what if I only want to print out the final total? 117.0 without the other 3.


#2

Hi, @systempro81720 ,

You have indented this statement ...

print total

, ... which makes it part of the for loop.

That is why it outputs intermediate values of total, rather than only the final value of total.


#3

Got it! Thanks a lot!


#4

Generic question here as it applies to this exercise:

I had to come to the forums because I wasn't sure that the code was really that "simple". Is it practice that makes you more comfortable? I tend to over think which gets me into more trouble than naught. Just curious.

BE


#5

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