Skip to content Skip to sidebar Skip to footer

Doubts About Python Variable Scope

Possible Duplicate: Short Description of Python Scoping Rules I wrote two simple functions: # coding: utf-8 def test(): var = 1 def print_var(): print var

Solution 1:

Yes, you're incorrect here. Function definition introduces a new scope.

# coding: utf-8
def test():
    var = 1 
    def print_var():
        print var    <--- var is not in local scope, the var from outer scope gets used
    print_var()
    print var 

test()
# 1
# 1
def test1():
    var = 2 
    def print_var():
        print var     <---- var is in local scope, but not defined yet, ouch
        var = 3 
    print_var()
    print var 

test1()
# raise Exception

Post a Comment for "Doubts About Python Variable Scope"