Scope and Recursion
Control where names exist and solve repeatable problems with safe recursive functions.
Where variables live
A variable made inside a function is local to that function. A variable made outside functions is global and can be read from inside a function.
A local name can shadow a global name with the same spelling.
message = "outside"
def show_message():
message = "inside"
print(message)
show_message()
print(message)
The local message shadows the global one only while show_message runs. After the call, the global value is still "outside".
Changing global variables
score = 0
def add_point():
global score
score = score + 1
add_point()
print(score)
Use global score only when a function must reassign a global variable. Passing values in and returning new values is usually easier to test and reuse.
color = "blue"
def paint(color):
print(color)
paint("red")
print(color)
A function that calls itself
Recursion means a function calls itself to solve a smaller version of the same problem. Every recursive function needs a base case, a condition that stops the calls.
def factorial(number):
if number == 0:
return 1
return number * factorial(number - 1)
print(factorial(5))
def fibonacci(number):
if number <= 1:
return number
return fibonacci(number - 1) + fibonacci(number - 2)
print(fibonacci(7))
Key points
- Local variables exist inside their function.
- A local name can shadow a global name.
- global allows reassignment of a global variable.
- Recursion solves a smaller version of the same problem.
- A base case stops recursive calls.
Worked example
Count down exam days with recursion — the function calls itself on a smaller problem until it hits the base case.
def countdown(days):
if days == 0:
return "Exam day!"
print(days)
return countdown(days - 1)
print(countdown(3))
How it works, step by step
- Each call prints the current number, then delegates to days-1.
- The base case (days == 0) stops the descent.
- Without a base case Python raises RecursionError.
References & Further Reading
Related entries from PyLabs's own reference library.
Practice exercise
Not passed yetWrite a recursive function named countdown. It should print the number, call itself with one less, and stop after printing 0. Call it with 3.
Expected output: 3
2
1
0
# Write your code below
Check yourself
Scope and Recursion quiz
10 questions. You get instant feedback per question, and the timer starts when you press the button.
Lesson incomplete
Not completedCreate an ID or sign in to save lesson completion across devices.