Define and call functions with clear responsibilities.
π§© Functions & Recursion
Organise programs into reusable units, pass information through parameters, return results and solve self-similar problems recursively.
def factorial(number):
if number <= 1:
return 1
return number * factorial(number - 1)
result = factorial(5)
print("Factorial =", result)By the End of This Level
You will be able to design reusable and well-structured Python solutions.
Use positional, keyword and default arguments correctly.
Return values and reason about local and global scope.
Build safe recursive solutions with a base case.
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.
An expression or statement that transfers control to a function and starts executing its body.
Define and Call a Function
def show_message():
print("Learn. Practice. Build.")
show_message()Learn. Practice. Build.
Parameters and Arguments
Parameters are names in a function definition; arguments are the actual values supplied during a call.
| Term | Location | Example |
|---|---|---|
| Parameter | Function definition | def greet(name): |
| Argument | Function call | greet("Bhavya") |
| Positional argument | Matched by order | area(8, 5) |
| Keyword argument | Matched by name | area(width=5, length=8) |
Use keyword arguments when names make a call easier to understand, especially when several parameters have similar value types.
Return Values
return ends the current function call and sends a result back to the caller.
Calculate and Return Area
def rectangle_area(length, width):
return length * width
area = rectangle_area(8, 5)
print("Area =", area)Area = 40
Display now
print() sends text to the output; it does not automatically make that value reusable.
Reuse later
return gives the result to the caller so it can be stored, compared or used in another expression.
Default and Keyword Arguments
A default parameter supplies a value when the caller omits that argument.
Power with a Default Exponent
def power(base, exponent=2):
return base ** exponent
print(power(6))
print(power(exponent=3, base=2))36 8
Parameters without defaults must appear before parameters with defaults in a function definition.
Local and Global Scope
Scope determines where a variable name can be accessed.
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 resultModule level
A name defined outside functions belongs to the global scope and can be read by functions.
course = "Python"
def show_course():
print(course)Prefer parameters and return values over changing global variables. This keeps functions predictable and easier to test.
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 requirement | Possible functions |
|---|---|
| Student result report | total_marks(), average(), grade() |
| Shopping bill | subtotal(), discount(), final_bill() |
| Number analysis | is_prime(), digit_sum(), reverse_number() |
Recursion Fundamentals
Recursion solves a problem by reducing it to a smaller version of the same problem.
Base Case
Stop immediately for the smallest known input.
if number <= 1:
return 1Recursive Case
Move toward the base case with a smaller input.
return number * factorial(number - 1)Every recursive path must eventually reach a base case. Otherwise calls continue until Python raises RecursionError.
Recursive Call Stack
Each recursive call gets its own local frame. Results are produced while those frames return in reverse order.
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
At runtime, Python must execute the def statement before it reaches the call.
A displayed value cannot replace a required return value in another calculation.
Supply every required argument exactly once unless a parameter has a default.
Recursive calls must reduce the problem and eventually stop.
π Functions & Recursion β Quick Revision
Review these rules before attempting the quiz and programming problems.
def creates a function definition.
Calling uses the function name followed by parentheses.
Parameters receive arguments supplied by the caller.
Positional arguments are matched by order.
Keyword arguments are matched by parameter name.
A default value makes an argument optional.
return ends a call and sends back a result.
Local variables belong to one function call.
Recursion requires a reachable base case.
Recursive results unwind in reverse call order.
π§ 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)?
π» CodeBhavya Function Challenges
Write and run each program in the browser. The checker uses the displayed sample input and exact expected output.
Read a name, pass it to a function and return a complete welcome message.
BhavyaExpected output: Welcome, Bhavya!Python Code Editor
Program Output
Run your program to see the output.
Test Case
def welcome(name):
return "Welcome, " + name + "!"
student = input()
print(welcome(student))Use separate functions to return a rectangleβs area and perimeter.
8, 5Expected output: Area = 40 and Perimeter = 26Python Code Editor
Program Output
Run your program to see the output.
Test Case
def area(length, width):
return length * width
def perimeter(length, width):
return 2 * (length + width)
length = int(input())
width = int(input())
print("Area =", area(length, width))
print("Perimeter =", perimeter(length, width))Return Positive, Negative or Zero from a decision-making function.
-7Expected output: Result = Negativereturn statements inside if and elif branches.Python Code Editor
Program Output
Run your program to see the output.
Test Case
def classify(number):
if number > 0:
return "Positive"
elif number < 0:
return "Negative"
return "Zero"
number = int(input())
print("Result =", classify(number))Read a non-negative integer and calculate its factorial recursively.
5Expected output: Factorial = 1201 for values at or below one; otherwise multiply by the factorial of one less.Python Code Editor
Program Output
Run your program to see the output.
Test Case
def factorial(number):
if number <= 1:
return 1
return number * factorial(number - 1)
number = int(input())
print("Factorial =", factorial(number))Read a positive integer and return the sum of its digits using recursion.
472Expected output: Digit Sum = 13Python Code Editor
Program Output
Run your program to see the output.
Test Case
def digit_sum(number):
if number == 0:
return 0
return number % 10 + digit_sum(number // 10)
number = int(input())
print("Digit Sum =", digit_sum(number))π― Build Small Functions with Clear Contracts
Give one function one responsibility.
Use meaningful parameters.
Send reusable data to the caller.
Reduce toward a base case.
π¬ Function Call β Visual Flow
Follow arguments into a function and observe how a returned value reaches the caller.
π§© How a Function Call Works
1. Define the Function
Python records the function name, parameters and body when it executes the def statement.
π Program Tracing β Recursive Factorial
Trace factorial(4) as calls build and returned values unwind.
Click Next to begin tracing.
β
π€ Functions & Recursion β Interview Questions
Answer aloud before opening each explanation.
What is the difference between a parameter and an argument?
A parameter is a name in a function definition. An argument is the actual value supplied to that parameter during a call.
What is the difference between print() and return?
print() displays information. return ends the function call and gives a value back to the caller for further use.
What is local scope?
Local scope contains parameters and variables belonging to one function call. Those names normally cannot be accessed outside the function.
Why should global-variable modification be limited?
Shared mutable state makes behavior harder to predict, test and reuse. Parameters and return values make dependencies explicit.
What are the two essential parts of recursion?
A recursion needs a base case that stops and a recursive case that moves the input toward that base case.
When is iteration preferable to recursion?
Iteration is often preferable for simple repetition because it avoids call-stack overhead and Pythonβs recursion-depth limit.
π‘ Functions & Recursion β Extra Tips
- 01
Name functions with verbs such as
calculate_total()oris_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.
βοΈ Functions & Recursion β Extra Practice Questions
- Write a function that returns the largest of three numbers.
- Create a function with a default tax percentage and return the final bill.
- Return whether a supplied number is prime.
- Build separate functions for total, average and grade.
- Write a recursive function to calculate a number raised to a power.
- Find the greatest common divisor recursively.
- Return the nth Fibonacci number recursively.
- Reverse a string using recursion.
- Count the digits of a positive integer recursively.
- 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.
