How Does This Work?


#1

Hi, it works, but I can not imagine how does it do it exactly.

Why my new variable related to the dictionary (fruit) sometimes is printed as a name (print fruit) and sometimes as a related value (print “price: %s” % prices[fruit])?

And why it does not print all fruits first, then all prices second, then all stocks third but instead it prints first fruit-price-stock combination, then second combination and so on?

for fruit in prices:
print fruit
print “price: %s” % prices[fruit]
print “stock: %s” % stock[fruit]

Thanks!


FAQ: Learn Python: A Day at the Supermarket - Keeping Track of the Produce
#2
for fruit in prices:
    print fruit
    print “price: %s” % prices[fruit]
    print “stock: %s” % stock[fruit]

The loop iterates through one fruit at a time, then the three lines inside the loop block execute in the order they are written.

orange
price: 3
stock: 6
pear
price: 1.5
stock: 9

I just fudged in the data, but you should get the point.


#3

Thank you! :slight_smile: