Function Scope

4.9. Function Scope#

Variables defined inside a function are only available within the function. This principle is know as the scope of the function and the variable exists in the local scope of that function. If a variable is used outside the scope in which it was defined, Python will throw a NameError.

Example

Here the variable y is created inside the function double, this means this variable only exists inside the function and we cannot print y outside the function. This results in a NameError (a variable of the specified name cannot be found).

def double(x):
    y = 2 * x


print(y)
Traceback (most recent call last):
    File "/home/main.py", line 4, in <module>
        print(y)
            ^
    NameError: name 'y' is not defined

Similarly, x is only created inside the function, and it also only exists inside the function, so we cannot print x outside the function and we get a NameError.

def double(x):
    y = 2 * x


print(x)
Traceback (most recent call last):
    File "/home/main.py", line 4, in <module>
        print(x)
            ^
    NameError: name 'x' is not defined

You can visualise this by drawing a box around your functions. Variables that are only defined inside the box cannot be seen outside the box. If it helps, you can make your box opaque to simulate your main program being unable to ‘see in’ to your function.

../../_images/scope1.png

Here you can see that to the rest of the program x and y don’t exist.

4.9.1. Global Scope#

While variables created inside functions cannot be seen outside of the function, any variable defined in the main program can still be seen inside the function. An example of where this might be useful is when defining constants.

Example

The function below calculates the speed of an object at time \(t\) after it has been dropped. The function is able to ‘see’ g, which stores the acceleration due to gravity since g is defined outside the function.

g = 9.8 # acceleration due to gravity (m/s^2)

def speed(time):
    return g*time

print(speed(5))
49.0
Question 1

Will the following code cause a NameError?

def add(x, y):
    s = x + y
    return s
Solution

No.

This code does not cause a NameError because s is defined within the local scope of the add function, and it is used within the same function.

Question 2

Will the following code cause a NameError?

x = 10

def check(x):
    if x < 20:
        return 'yes'
    else:
        return 'no'

print(x)
Solution

This code does not cause a NameError because x is defined within the global scope of the program, and can be used at all points in the program. You can imagine drawing a box over the function to check what variables the main program can ‘see’.

../../_images/scope2.png
Question 3

What do you expect the output of the following code to be?

x = 10

def check(x):
    if x < 20:
        return 'yes'
    else:
        return 'no'

print(check(50))
  1. 10
    
  2. 50
    
  3. yes
    
  4. no
    
Solution

Solution is locked

Question 4

What do you expect the output of the following code to be?

x = 10

def check(x):
    if x < 20:
        return 'yes'
    else:
        return 'no'

check(50)
print(x)
  1. 10
    
  2. 50
    
  3. yes
    
  4. no
    
Solution

Solution is locked

Question 5

What is the value of price printed, when this Python code is run?

price = 100

def change_price(new_price):
    price = new_price

change_price(500)

print(price)
  1. 100

  2. 500

  3. This code has a NameError

Solution

Solution is locked

Question 6

Will the following code cause a NameError?

a = 10
b = 2
c = 3

def quadratic(x):
    return a * x**2 + b*x + c

print(A)
Solution

Solution is locked

Code challenge: Energy

Write a function to calculate the energy of an object in its rest frame given the mass.

Formula

\(e = mc^2\)

where \(c = 299 792 458`\) m/s.

Function specification

  • name: energy

  • parameters: mass (float)

  • return: energy (float)

Example 1

print(energy(100))
8.987551787368176e+18

Example 2

print(energy(0))
0.0
Solution

Solution is locked

Code challenge: Volume Of A Cylinder

Write a function to calculate the volume of a cylinder.

Formula

Volume of a cylinder

\(v = \pi r^2 h\)

where \(r\) is the radius and \(h\) is the height. The value of \(\pi\) can be accessed from the math module.

Function specification

  • name: cylinder_volume

  • parameters: radius (float), height (float)

  • return: the volume of the cylinder (float)

Example 1

print(cylinder_volume(2, 10))
125.66370614359172

Example 2

print(cylinder_volume(5, 5))
392.69908169872417
Solution

Solution is locked

Code challenge: 8-ball
../../_images/8ball.gif

A magic 8-ball is a special ball that can help you make a decision. Write a function called eight_ball that mimics a magic 8-ball by randomly choosing one of the following messages to display.

Message 1

Reply hazy, try again

Message 2

Signs point to yes

Message 3

You may rely on it

Function specification

  • name: eight_ball

  • parameters: None

  • return: message (str)

Solution

Solution is locked

Code challenge: Fibonacci

The Fibonacci sequence is:

\(1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ...\)

The first two terms are defined to be:

\(F_1 = 1, F_2 = 1\)

With all remaining terms defined as:

\(F_n = F_{n-1} + F_{n-2}\)

Write a function called fibonacci which, when given an integer, \(n\), will calculate the \(n^{th}\) number in the Fibonacci sequence.

Function specification

  • function name: fibonacci

  • parameters: n (int)

  • return: \(F_n\) (int)

Example 1

print(fibonacci(6))
8

Example 2

print(fibonacci(10))
55