Functions – Scope, online

Six activities your students do on their own devices. See who's finished, and their scores.

Functions – Scope in one minute

What students need to know

Functions can read global variables without the 'global' keyword. 'global count' declares that count refers to the global variable.

Local variables only exist inside the function they're created in. Global variables are defined at the top level and accessible everywhere.

Mistakes students make

  • x is local to func it can't be accessed outside. Print inside the function.
  • x is local and dies when func ends. Use return to get the value out.
  • result is local to add. Return the value and store it outside.
  • The local name inside change doesn't affect the global name. Use return.

Discover other journeys with this module

What students will learn in this module

Every question in Module 27

Quick questions

  1. What is a local variable?AA variable created inside a functionBA variable outside all functions
  2. What is a global variable?AA variable inside a functionBA variable created outside all functions
  3. def func():\n x = 5\nprint(x)\nWhat happens?APrints 5BNameError x doesn't exist outside func
  4. x = 10\ndef show():\n print(x)\nshow()\nWhat prints?A10BError
  5. When does a local variable stop existing?AWhen the function finishesBWhen the program ends

Key terms

Students type the meaning of:

  • Scope
  • Local variable
  • Global variable
  • NameError

Match the pairs

def func():
    x = 10
print(x)
Match it to what it does
count = 0
def add_one():
    count += 1
Match it to what it does
x = 5
def show():
    print(x)
show()
Match it to what it does
count = 0
def add():
    global count
    count += 1
Match it to what it does
def func():
    y = 99
func()
print(y)
Match it to what it does
msg = 'Hi'
def greet():
    print(msg)
greet()
Match it to what it does

Fill in the blanks

  1. def func():
        x = 5
    # x is a _____ variable
  2. x = 10
    # x is a ______ variable
    def func():
        print(x)
  3. def func():
        y = 5
    
    func()
    print(y)
    # causes _________Error
  4. x = 'outside'
    def func():
        x = 'inside'
        print(x)
    # prints ________
  5. def add(a, b):
        result = a + b
        ______ result

Spot the error

Question 1

Adef func():B    x = 5CDprint(x)

Question 2

Adef func():B    x = 5CDfunc()Eprint(x)

Question 3

Adef add(a, b):B    result = a + bCDadd(3, 5)Eprint(result)

Question 4

Aname = 'Alice'Bdef change():C    name = 'Bob'DEchange()Fprint(name)  # expects Bob

Question 5

Adef greet():B    msg = 'Hello'CDdef show():E    print(msg)