Indentation in for loop


#1



So while doing this problem I encountered a situation:

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

If i use these codes the total is calculated as zero.


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 key in prices:
    asset = prices[key] * stock[key]
    print asset 
total = asset + total
print total

However if I indent "total = asset + total", it works out just fine.

My question is two part:
1. Why is it that indentation matters in this case? Is an assignment (asset in this case) in a for loop not global?
2. If an variable under a for loop is indeed not global, then if invoked outside the for loop the variable has a default value of zero? I am assuming this because "total" equals zero in my wrong codes


#2

Code blocks are containers denoted by common indentation on the contents. Your total addition line is outside of the code block of your for loop.


#3

So code blocks are like separate universes, and what I do inside one has no bearing on anything outside?


#4

Yes and no. Functions have their own scope, where if, while and for do not. The execution context is defined by the block.


#5

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