Functions & Files · Unit 4

User-Defined Functions & Recursion

Parameters, return, scope and recursion

Unit 4 · Reusable logic

A function gives a name to a useful operation

Define a function once, then call it whenever you need that operation. Parameters let a caller provide data; a return value lets the caller use the result. This section builds a function in small runnable steps, then traces recursion and variable scope.

Build a function one idea at a time

Use the step controls to reveal the concept, inspect its code, and run it.

Step 1 of 4

1 · Define the function

def starts a function definition. The indented body runs only when the function is called.

Vocabulary

A parameter is the variable named in a definition. An argument is the actual value passed when calling the function.

Build and run
Starting up Python…
def greet():
    print("Welcome to Python lab!")
The editor is ready while Python loads in the background.

Output

Your program's output will appear here.
Common Python mistakes

NameError: name 'mark' is not defined

NameError: A name was used before Python could find a variable or function with that name.

IndexError: list index out of range

IndexError: The requested position is outside the items in this list or sequence.

KeyError: 'email'

KeyError: That key does not exist in this dictionary.

TypeError: can only concatenate str (not "int") to str

TypeError: This operation does not work with the kind of value it received.

ZeroDivisionError: division by zero

ZeroDivisionError: A number cannot be divided by zero.

SyntaxError: invalid syntax

SyntaxError: Python could not understand the structure of this line. Check spelling, brackets, colons, and quotes.

IndentationError: expected an indented block

IndentationError: The spaces at the start of a line do not match Python's block structure.

Recursion: a function calls itself

Factorial is the product of all positive integers up to n. The recursive rule is factorial(n) = n × factorial(n − 1), with factorial(1) = 1 as the stopping case. A correct recursive function must move toward that base case.

Factorial in Python
Starting up Python…
def factorial(n):
    if n == 1:  # base case
        return 1
    return n * factorial(n - 1)  # recursive case

print(factorial(4))
The editor is ready while Python loads in the background.

Output

Your program's output will appear here.
Common Python mistakes

NameError: name 'mark' is not defined

NameError: A name was used before Python could find a variable or function with that name.

IndexError: list index out of range

IndexError: The requested position is outside the items in this list or sequence.

KeyError: 'email'

KeyError: That key does not exist in this dictionary.

TypeError: can only concatenate str (not "int") to str

TypeError: This operation does not work with the kind of value it received.

ZeroDivisionError: division by zero

ZeroDivisionError: A number cannot be divided by zero.

SyntaxError: invalid syntax

SyntaxError: Python could not understand the structure of this line. Check spelling, brackets, colons, and quotes.

IndentationError: expected an indented block

IndentationError: The spaces at the start of a line do not match Python's block structure.

Call stack · factorial(4)

Each frame remembers its own n while waiting for the deeper call.

factorial(4) · current

Step 1 of 8

Waiting for factorial(3)

4 is not the base case, so this call asks for 4 × factorial(3).

The call-stack panel is a teaching trace of factorial(4); the adjacent runner executes the Python function itself.

Scope: where a name can be used

A local variable belongs to a function call. It can temporarily have the same name as a global variable; the local name shadows the global name inside that function. Outside the function, the global value is still available.

Local shadows global

Inside the function, Python uses the local name. After return, the outer value remains unchanged.

Scope example
Starting up Python…
student = "Mira"  # global

def greet():
    student = "Dev"  # local; shadows the global here
    print("Inside:", student)

greet()
print("Outside:", student)
The editor is ready while Python loads in the background.

Output

Your program's output will appear here.
Common Python mistakes

NameError: name 'mark' is not defined

NameError: A name was used before Python could find a variable or function with that name.

IndexError: list index out of range

IndexError: The requested position is outside the items in this list or sequence.

KeyError: 'email'

KeyError: That key does not exist in this dictionary.

TypeError: can only concatenate str (not "int") to str

TypeError: This operation does not work with the kind of value it received.

ZeroDivisionError: division by zero

ZeroDivisionError: A number cannot be divided by zero.

SyntaxError: invalid syntax

SyntaxError: Python could not understand the structure of this line. Check spelling, brackets, colons, and quotes.

IndentationError: expected an indented block

IndentationError: The spaces at the start of a line do not match Python's block structure.

Prefer explicit data flow

Parameters and return values make dependencies visible and keep functions easier to reuse.

Pass and return values
Starting up Python…
def add_bonus(mark, bonus):
    return mark + bonus

updated_mark = add_bonus(82, 5)
print(updated_mark)
The editor is ready while Python loads in the background.

Output

Your program's output will appear here.
Common Python mistakes

NameError: name 'mark' is not defined

NameError: A name was used before Python could find a variable or function with that name.

IndexError: list index out of range

IndexError: The requested position is outside the items in this list or sequence.

KeyError: 'email'

KeyError: That key does not exist in this dictionary.

TypeError: can only concatenate str (not "int") to str

TypeError: This operation does not work with the kind of value it received.

ZeroDivisionError: division by zero

ZeroDivisionError: A number cannot be divided by zero.

SyntaxError: invalid syntax

SyntaxError: Python could not understand the structure of this line. Check spelling, brackets, colons, and quotes.

IndentationError: expected an indented block

IndentationError: The spaces at the start of a line do not match Python's block structure.

Common function mistakes

Missing call

def greet(): ...

Defining a function stores its instructions; call greet() to execute them.

No return value

result = print(5)

print displays a value and returns None. Use return when a caller needs a result.

Missing base case

Recursive calls never approach a stopping condition.

Without a base case Python eventually raises RecursionError. Ensure each step moves toward it.

Local name unavailable outside

Reading a function's local variable after it returns.

Local variables belong to that call. Return a value if it must be used outside.

Check your understanding

1. In def greet(name):, what is name?

2. Why does a recursive function need a base case?

3. What does a function return if it reaches the end without return?