PART 3 β€’ LEVEL 09

🧩 Functions & Recursion

Organise programs into reusable units, pass information through parameters, return results and solve self-similar problems recursively.

⏱ 105–120 minutesπŸ“š 8 conceptsπŸ’» 5 programs🧠 6-question quiz
factorial.pyPython 3
def factorial(number):
    if number <= 1:
        return 1
    return number * factorial(number - 1)

result = factorial(5)
print("Factorial =", result)
OUTPUTFactorial = 120

By the End of This Level

You will be able to design reusable and well-structured Python solutions.

01

Define and call functions with clear responsibilities.

02

Use positional, keyword and default arguments correctly.

03

Return values and reason about local and global scope.

04

Build safe recursive solutions with a base case.

01

Function Fundamentals

A function is a named block of reusable code that performs one focused task.

Define a function with def, give it a meaningful name, place its body inside an indented block and call it using parentheses.

Function call

An expression or statement that transfers control to a function and starts executing its body.

1DefineCreate named logic
β†’
2CallRequest execution
β†’
3ExecuteRun function body
β†’
4ResumeContinue caller
EXAMPLE 1

Define and Call a Function

def show_message():
    print("Learn. Practice. Build.")

show_message()
Output
Learn. Practice. Build.
02

Parameters and Arguments

Parameters are names in a function definition; arguments are the actual values supplied during a call.

TermLocationExample
ParameterFunction definitiondef greet(name):
ArgumentFunction callgreet("Bhavya")
Positional argumentMatched by orderarea(8, 5)
Keyword argumentMatched by namearea(width=5, length=8)
Clear calls

Use keyword arguments when names make a call easier to understand, especially when several parameters have similar value types.

03

Return Values

return ends the current function call and sends a result back to the caller.

EXAMPLE 2

Calculate and Return Area

def rectangle_area(length, width):
    return length * width

area = rectangle_area(8, 5)
print("Area =", area)
Output
Area = 40
PRINT

Display now

print() sends text to the output; it does not automatically make that value reusable.

RETURN

Reuse later

return gives the result to the caller so it can be stored, compared or used in another expression.

04

Default and Keyword Arguments

A default parameter supplies a value when the caller omits that argument.

EXAMPLE 3

Power with a Default Exponent

def power(base, exponent=2):
    return base ** exponent

print(power(6))
print(power(exponent=3, base=2))
Output
36
8
Parameter order

Parameters without defaults must appear before parameters with defaults in a function definition.

05

Local and Global Scope

Scope determines where a variable name can be accessed.

LOCAL

Inside one call

A parameter or variable created inside a function normally exists only during that function call.

def calculate(value):
    result = value * 2
    return result
GLOBAL

Module level

A name defined outside functions belongs to the global scope and can be read by functions.

course = "Python"

def show_course():
    print(course)
Best practice

Prefer parameters and return values over changing global variables. This keeps functions predictable and easier to test.

06

Function Decomposition

Break a large task into small functions with one clear responsibility each.

🧭

Readable

Names explain the program’s major steps.

♻️

Reusable

One implementation can serve many calls.

πŸ§ͺ

Testable

Each unit can be checked independently.

πŸ› οΈ

Maintainable

Changes remain focused and safer.

Large requirementPossible functions
Student result reporttotal_marks(), average(), grade()
Shopping billsubtotal(), discount(), final_bill()
Number analysisis_prime(), digit_sum(), reverse_number()
07

Recursion Fundamentals

Recursion solves a problem by reducing it to a smaller version of the same problem.

RULE 1

Base Case

Stop immediately for the smallest known input.

if number <= 1:
    return 1
RULE 2

Recursive Case

Move toward the base case with a smaller input.

return number * factorial(number - 1)
Safety rule

Every recursive path must eventually reach a base case. Otherwise calls continue until Python raises RecursionError.

08

Recursive Call Stack

Each recursive call gets its own local frame. Results are produced while those frames return in reverse order.

1factorial(4)Wait for 3!
β†’
2factorial(3)Wait for 2!
β†’
3factorial(2)Wait for 1!
β†’
4factorial(1)Return base value

The stack first grows: 4 β†’ 3 β†’ 2 β†’ 1. It then unwinds: 1 β†’ 2 β†’ 6 β†’ 24. A recursive function therefore has a calling phase and a returning phase.

Function Errors to Avoid

01
Calling before definition

At runtime, Python must execute the def statement before it reaches the call.

02
Printing instead of returning

A displayed value cannot replace a required return value in another calculation.

03
Wrong argument count

Supply every required argument exactly once unless a parameter has a default.

04
Missing base case

Recursive calls must reduce the problem and eventually stop.

QUICK REVISION

πŸ“Œ Functions & Recursion β€” Quick Revision

Review these rules before attempting the quiz and programming problems.

01

def creates a function definition.

02

Calling uses the function name followed by parentheses.

03

Parameters receive arguments supplied by the caller.

04

Positional arguments are matched by order.

05

Keyword arguments are matched by parameter name.

06

A default value makes an argument optional.

07

return ends a call and sends back a result.

08

Local variables belong to one function call.

09

Recursion requires a reachable base case.

10

Recursive results unwind in reverse call order.

KNOWLEDGE CHECK

🧠 Functions & Recursion Quiz

Choose one answer for each question, then check your score.

1. Which keyword defines a Python function?

2. What does return do?

3. Which call uses keyword arguments?

4. Where does a parameter normally exist?

5. What prevents infinite recursion?

6. What is the value of factorial(4)?

PROGRAMMING PROBLEMS

πŸ’» CodeBhavya Function Challenges

Write and run each program in the browser. The checker uses the displayed sample input and exact expected output.

πŸ“ˆ Functions Practice Progress
Solved independently0 / 5
Completed with solution0
Best score0 / 500
Progress0%
1. Personalised Welcome

Read a name, pass it to a function and return a complete welcome message.

Sample input: BhavyaExpected output: Welcome, Bhavya!
2. Rectangle Report

Use separate functions to return a rectangle’s area and perimeter.

Sample input: 8, 5Expected output: Area = 40 and Perimeter = 26
3. Classify a Number

Return Positive, Negative or Zero from a decision-making function.

Sample input: -7Expected output: Result = Negative
4. Recursive Factorial

Read a non-negative integer and calculate its factorial recursively.

Sample input: 5Expected output: Factorial = 120
5. Recursive Digit Sum

Read a positive integer and return the sum of its digits using recursion.

Sample input: 472Expected output: Digit Sum = 13
KEY TAKEAWAY

🎯 Build Small Functions with Clear Contracts

1Define Purpose

Give one function one responsibility.

β†’
2Receive Inputs

Use meaningful parameters.

β†’
3Return Result

Send reusable data to the caller.

β†’
4Recurse Safely

Reduce toward a base case.

Functions improve structure through reuse and separation of concerns. Recursion is powerful when the problem naturally becomes a smaller version of itself and every path reaches a base case.

INTERACTIVE LEARNING

🎬 Function Call β€” Visual Flow

Follow arguments into a function and observe how a returned value reaches the caller.

PROGRAM TRACING

πŸ”Ž Program Tracing β€” Recursive Factorial

Trace factorial(4) as calls build and returned values unwind.

INTERVIEW PREPARATION

🎀 Functions & Recursion β€” Interview Questions

Answer aloud before opening each explanation.

1.

What is the difference between a parameter and an argument?

2.

What is the difference between print() and return?

3.

What is local scope?

4.

Why should global-variable modification be limited?

5.

What are the two essential parts of recursion?

6.

When is iteration preferable to recursion?

EXTRA TIPS

πŸ’‘ Functions & Recursion β€” Extra Tips

  • 01

    Name functions with verbs such as calculate_total() or is_prime().

  • 02

    Keep one function focused on one clear responsibility.

  • 03

    Prefer returned values when a result must be reused or tested.

  • 04

    Place required parameters before parameters that have defaults.

  • 05

    Trace small recursive inputs manually before testing larger values.

  • 06

    Check both the base case and the step that moves toward it.

EXTRA PRACTICE

✍️ Functions & Recursion β€” Extra Practice Questions

  1. Write a function that returns the largest of three numbers.
  2. Create a function with a default tax percentage and return the final bill.
  3. Return whether a supplied number is prime.
  4. Build separate functions for total, average and grade.
  5. Write a recursive function to calculate a number raised to a power.
  6. Find the greatest common divisor recursively.
  7. Return the nth Fibonacci number recursively.
  8. Reverse a string using recursion.
  9. Count the digits of a positive integer recursively.
  10. Explain the call stack for factorial(5).

Functions & Recursion Complete

When you can design clear functions, return reusable values, explain scope and trace recursive calls safely, mark this level complete and continue.