Skip to content

Scope and Recursion

Control where names exist and solve repeatable problems with safe recursive functions.

12 min read 10 quiz questions

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.

Example 1: Local scope and shadowing
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

Example 2: Change a global name
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.

Example 3: A parameter can shadow a global
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.

Example 4: Factorial with recursion
def factorial(number):
    if number == 0:
        return 1
    return number * factorial(number - 1)

print(factorial(5))
Example 5: Fibonacci with recursion
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.

Example
def countdown(days):
    if days == 0:
        return "Exam day!"
    print(days)
    return countdown(days - 1)

print(countdown(3))

How it works, step by step

  1. Each call prints the current number, then delegates to days-1.
  2. The base case (days == 0) stops the descent.
  3. Without a base case Python raises RecursionError.

References & Further Reading

Related entries from PyLabs's own reference library.

  • globals() (Return the current global namespace dictionary.)
  • locals() (Get the local names currently available in this part of the code.)

Your notes

Sign in to keep private notes alongside this lesson.

Sign in to take notes

Practice exercise

Not passed yet

Write 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
Want another challenge on this module? More coding practice

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 completed

Create an ID or sign in to save lesson completion across devices.

Create ID to save
Module lesson progress0/5 complete
Module cheat sheet