Functions – Scope, online
Six activities your students do on their own devices. See who's finished, and their scores.
Learning
Understanding
Testing
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.
PREVIOUS · MODULE 26Functions – Return Values
YOU ARE HERE · MODULE 27Functions – Scope
NEXT · MODULE 28Functions – Default Arguments
What students will learn in this module
Every question in Module 27
Quick questions
- What is a local variable?AA variable created inside a functionBA variable outside all functions
- What is a global variable?AA variable inside a functionBA variable created outside all functions
- def func():\n x = 5\nprint(x)\nWhat happens?APrints 5BNameError x doesn't exist outside func
- x = 10\ndef show():\n print(x)\nshow()\nWhat prints?A10BError
- When does a local variable stop existing?AWhen the function finishesBWhen the program ends
Key terms
Students type the meaning of:
ScopeLocal variableGlobal variableNameError
Match the pairs
def func():
x = 10
print(x)Match it to what it doescount = 0
def add_one():
count += 1Match it to what it doesx = 5
def show():
print(x)
show()Match it to what it doescount = 0
def add():
global count
count += 1Match it to what it doesdef func():
y = 99
func()
print(y)Match it to what it doesmsg = 'Hi'
def greet():
print(msg)
greet()Match it to what it doesFill in the blanks
def func(): x = 5 # x is a _____ variablex = 10 # x is a ______ variable def func(): print(x)def func(): y = 5 func() print(y) # causes _________Errorx = 'outside' def func(): x = 'inside' print(x) # prints ________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)
