Scope


Scope
Variables can only reach the area in which they are defined, which is called scope. Think of it as the area of code where variables can be used. Python supports global variables (usable in the entire program) and local variables.

By default, all variables declared in a function are local variables. To access a global variable inside a function, it’s required to explicitly define ‘global variable’.

Related course
Complete Python Bootcamp: Go from zero to hero in Python

Example
Below we’ll examine the use of local variables and scope. This will not work:

#!/usr/bin/python
 
def f(x,y):
    print('You called f(x,y) with the value x = ' + str(x) + ' and y = ' + str(y))
    print('x * y = ' + str(x*y))
    z = 4 # cannot reach z, so THIS WON'T WORK
 
z = 3
f(3,2)

but this will:

#!/usr/bin/python
 
def f(x,y):
    z = 3
    print('You called f(x,y) with the value x = ' + str(x) + ' and y = ' + str(y))
    print('x * y = ' + str(x*y))
    print(z) # can reach because variable z is defined in the function
 
f(3,2)

Let’s examine this further:

#!/usr/bin/python
 
def f(x,y,z):
    return x+y+z # this will return the sum because all variables are passed as parameters
 
sum = f(3,2,1)
print(sum)

Calling functions in functions
We can also get the contents of a variable from another function:

#!/usr/bin/python
 
def highFive():
    return 5
 
def f(x,y):
    z = highFive() # we get the variable contents from highFive()
    return x+y+z # returns x+y+z. z is reachable becaue it is defined above
 
result = f(3,2)
print(result)

If a variable can be reached anywhere in the code is called a global variable. If a variable is known only inside the scope, we call it a local variable.

Global and Local variables
Loops: For loop, while loop

7 thoughts on “Scope

  1. Greg - July 23, 2017

    To follow up on Carl’s comment, the supplied example in the tutorial (with the bold, italic “this will not work”) also works fine for me in Python 3.6. I thought I’d let everyone know what I discovered while experimenting to find what would and would not work.

    Without using the keyword ‘global’…

    You can reference a global variable inside a function. This code works fine, and prints the global value of z (10) twice:

    def testing_scope():
        print(z)
     
    z = 10
    testing_scope()
    print(z)

    You can also create a local variable with the same name inside a function. This code works fine, and prints the local value of z (1) followed by the global value of z (10):

    def testing_scope():
        z = 1
        print(z)
     
    z = 10
    testing_scope()
    print(z)

    However, you cannot first reference global variable then create a local variable with the same name. Trying to define testing_scope like this does not work:

    def testing_scope():
        print(z)
        z = 1

    I hope that helps clarify things!

    1. Greg - July 23, 2017

      My apologies for the indentation not showing up properly. I would edit if I could.

      1. Frank - July 26, 2017

        No problem, all indented correctly now 🙂

  2. Carl Wainwright - August 28, 2016

    I ran this code in v2.7.10 and it executed without any errors

    def f(x,y):
        print('You called f(x,y) with the value x = ' + str(x) + ' and y = ' + str(y))
        print('x * y = ' + str(x*y))
        z = 4 # cannot reach z, so THIS WON'T WORK
        print(z)
     
    z = 3
    f(3,2)
    MacBookAir:.ssh carlwainwright$ python ~/Projects/Python/helloworld.py 
    You called f(x,y) with the value x = 3 and y = 2
    x * y = 6
    4
    1. Frank - August 28, 2016

      Try this program:

      def showz():
          print(z)
       
      def f(x,y):
          print('You called f(x,y) with the value x = ' + str(x) + ' and y = ' + str($
          print('x * y = ' + str(x*y))
          z = 4 # cannot reach z, so THIS WON'T WORK
          print(z)
       
      z = 3
      f(3,2)
      showz()

      In this example z will still be 3 after calling f(3,2). Sorry for the confusion, ill update

      1. Carl Wainwright - August 29, 2016

        So without “global z” in function ‘f’ z is local to the function and when you return back the global z is scoped.

        1. Frank - August 31, 2016

          Correct, otherwise the changed occur only locally