Python-Ref > Basic usage > Functions > Scope of variables used inside functions
 
 

<-^^->
Moduly
Knihovní funkce

Scope of variables used inside functions

What is the lifetime of a variable used inside a function?
Variables that are defined and used inside the body of a function do not exist outside of the scope of the function.
Expand/Shrink
Zdroj: (func6-1.py)
  1   def times3( x):
  2       result = 3*x
  3       print "result =", result
  4       return result
  5   
  6   print times3( 10)
  7   print "result =", result   # 'result' does not exist in this scope
stdout:
result = 30
30
result =
stderr:
Traceback (most recent call last):
  File "func6-1.py", line 8, in ?
    print "result =", result   # 'result' does not exist in this scope
NameError: name 'result' is not defined
Doba běhu: 21.1 ms
Local variables (variables declared inside a function) "shadow" variables with the same name defined outside the function.
Expand/Shrink
Zdroj: (func6-2.py)
  1   x = 200
  2   
  3   def times2( y):
  4       print "x inside times2 is:", x
  5       return 2*y
  6   
  7   def times3( x):
  8       print "x inside times3 is:", x
  9       return 3*x
 10   
 11   times2( 10)
 12   times3( 10)
 13   print "x outside is:", x   # still the outside value
stdout:
x inside times2 is: 200
x inside times3 is: 10
x outside is: 200
Doba běhu: 21.4 ms
Even setting the value of an outside variable is not possible inside a function - you will create a local variable instead.
Expand/Shrink
Zdroj: (func6-3.py)
  1   value = 200
  2   
  3   def times3( x):
  4       value = 100
  5       print "value inside function is:", value
  6       return 3*x
  7   
  8   times3( 10)
  9   print "value outside is:", value   # still the outside value
stdout:
value inside function is: 100
value outside is: 200
Doba běhu: 21.0 ms
To really modify the outside value, the variable must be at first declared as global.
Expand/Shrink
Zdroj: (func6-4.py)
  1   value = 200
  2   
  3   def times3( x):
  4       global value
  5       value = 100
  6       print "value inside function is:", value
  7       return 3*x
  8   
  9   print "value outside is:", value   # still the outside value
 10   times3( 10)
 11   print "value outside is:", value   # the outside value was changed
stdout:
value outside is: 200
value inside function is: 100
value outside is: 100
Doba běhu: 20.9 ms
The scoping also applies to modules imported inside a function.
Expand/Shrink
Zdroj: (func6-5.py)
  1   def import_func():
  2     import string
  3     print string
  4   
  5   import_func()
  6   print string  # string does not exist outside the function scope  
stdout:
<module 'string' from '/usr/lib/python2.4/string.pyc'>
stderr:
Traceback (most recent call last):
  File "func6-5.py", line 6, in ?
    print string  # string does not exist outside the function scope  
NameError: name 'string' is not defined
Doba běhu: 23.6 ms