MODULE 04

Python Functions

Master functions from the basics to practical programming: defining and calling functions, parameters, arguments, return values, scope, *args, **kwargs, lambda, recursion and function design.

9Major Topics
31Coding Questions
31Theory Q&A
Step-by-StepTeaching Style

Module Contents

1. Functions2. Parameters3. Return Values4. Scope5. Argument Patterns6. Best Practices7. Lambda8. Recursion9. WorkflowCoding PracticeTheory Q&A

1. Introduction to Functions

A function is a reusable block of code designed to perform a specific task. Functions make programs easier to organize, test, reuse and maintain.

1.1 Why Functions?

1.2 Defining and Calling a Function

def greet():
    print("Hello, Python!")

greet()
Step by step:
  1. def starts the definition.
  2. greet is the function name.
  3. Parentheses hold parameters when needed.
  4. The indented block is the function body.
  5. greet() calls the function.

1.3 Function Execution

def message():
    print("Welcome")

print("Before")
message()
print("After")

Defining a function does not execute its body. The body runs when the function is called.

2. Parameters and Arguments

Parameters are variables in a function definition. Arguments are actual values supplied during the call.

2.1 One and Multiple Parameters

def greet(name):
    print("Hello", name)

greet("Ravi")

def add(a, b):
    return a + b

print(add(10, 20))

2.2 Positional Arguments

def student(name, age):
    print(name, age)

student("Ravi", 22)

Arguments are matched according to their position.

2.3 Keyword Arguments

def student(name, age):
    print(name, age)

student(age=22, name="Ravi")

2.4 Default Parameters

def greet(name="Student"):
    print("Hello", name)

greet()
greet("Anu")

2.5 *args

def total(*numbers):
    return sum(numbers)

print(total(10, 20, 30, 40))

*args collects extra positional arguments into a tuple.

2.6 **kwargs

def show_profile(**details):
    for key, value in details.items():
        print(key, value)

show_profile(name="Ravi", age=22, city="Hyderabad")

**kwargs collects extra keyword arguments into a dictionary.

3. Return Values

return sends a result back to the caller and immediately ends that function execution.

3.1 print() vs return

def add_print(a, b):
    print(a + b)

def add_return(a, b):
    return a + b

result = add_return(10, 20)
print(result)

print() displays information; return creates a reusable result.

3.2 Returning Multiple Values

def calculate(a, b):
    return a + b, a - b, a * b

s, d, p = calculate(10, 5)
print(s, d, p)

Multiple returned values are commonly packed into a tuple.

3.3 Early Return

def check_age(age):
    if age < 18:
        return "Minor"
    return "Adult"

print(check_age(20))

3.4 No Explicit Return

def hello():
    print("Hello")

result = hello()
print(result)  # None

4. Scope of Variables

Scope determines where a variable name can be accessed.

4.1 Local Variable

def show():
    x = 10
    print(x)

show()
# print(x)  # NameError

4.2 Global Variable

x = 100

def show():
    print(x)

show()

4.3 Local vs Global with Same Name

x = 100

def test():
    x = 50
    print("Inside:", x)

test()
print("Outside:", x)

The local variable shadows the global variable inside the function.

4.4 global Keyword

count = 0

def increment():
    global count
    count += 1

increment()
print(count)

4.5 LEGB Rule

Python generally searches for names in this order: Local → Enclosing → Global → Built-in.

4.6 nonlocal Keyword

def outer():
    x = 10

    def inner():
        nonlocal x
        x += 5

    inner()
    print(x)

outer()

5. Practical Argument Patterns

5.1 Passing a List

def total_marks(marks):
    return sum(marks)

print(total_marks([80, 90, 85]))

5.2 Passing a Dictionary

def show_student(student):
    print(student["name"])
    print(student["marks"])

show_student({"name": "Ravi", "marks": 90})

5.3 Mutable Arguments

def add_item(items):
    items.append("Python")

skills = ["SQL"]
add_item(skills)
print(skills)

Mutable objects such as lists can be changed by operations performed inside a function.

6. Function Design and Best Practices

6.1 One Main Responsibility

def calculate_average(marks):
    return sum(marks) / len(marks)

Small focused functions are easier to test and reuse.

6.2 Docstrings

def square(number):
    '''Return the square of a number.'''
    return number * number

print(square.__doc__)

6.3 Type Hints

def add(a: int, b: int) -> int:
    return a + b

Type hints document intended types; Python generally does not enforce them automatically at runtime.

6.4 Naming

Prefer descriptive lowercase names with underscores, such as calculate_total() and find_maximum().

7. Lambda Functions

A lambda is a small anonymous function used for short expressions.

7.1 Basic Lambda

square = lambda x: x * x
print(square(5))

7.2 Multiple Parameters

add = lambda a, b: a + b
print(add(10, 20))

7.3 Lambda with sorted()

students = [("Ravi", 80), ("Anu", 95), ("Kiran", 75)]
students.sort(key=lambda item: item[1])
print(students)

8. Recursion

Recursion occurs when a function calls itself. A recursive function needs a base case to stop.

8.1 Recursive Factorial

def factorial(n):
    if n == 0:
        return 1
    return n * factorial(n - 1)

print(factorial(5))
Trace: factorial(5) → 5 × factorial(4) → 5 × 4 × factorial(3) → ... → factorial(0) = 1.

8.2 Why Base Cases Matter

Without a stopping condition, recursive calls can continue until Python reaches its recursion limit.

9. Practical Function Workflow

  1. Identify the task.
  2. Decide required inputs.
  3. Choose parameters.
  4. Write the logic.
  5. Decide whether to print or return.
  6. Call the function.
  7. Test normal and boundary cases.

9.1 Student Result Example

def result(marks):
    average = sum(marks) / len(marks)

    if average >= 40:
        return "Pass"
    return "Fail"

print(result([70, 65, 80]))

9.2 Common Mistakes

31 Coding Questions — Step-by-Step Solutions

Try each problem yourself first, then reveal the solution.

01
Create a simple function

Define a function that prints Hello Python and call it.

  1. Identify the required inputs and output.
  2. Define the function using def.
  3. Write the required logic inside the indented body.
  4. Call the function and inspect the result.
def hello():
    print("Hello Python")

hello()
02
One parameter

Create greet(name) that prints a greeting.

  1. Identify the required inputs and output.
  2. Define the function using def.
  3. Write the required logic inside the indented body.
  4. Call the function and inspect the result.
def greet(name):
    print("Hello", name)

greet("Ravi")
03
Add two numbers

Return the sum of two numbers.

  1. Identify the required inputs and output.
  2. Define the function using def.
  3. Write the required logic inside the indented body.
  4. Call the function and inspect the result.
def add(a, b):
    return a + b

print(add(10, 20))
04
Subtract two numbers

Return a - b.

  1. Identify the required inputs and output.
  2. Define the function using def.
  3. Write the required logic inside the indented body.
  4. Call the function and inspect the result.
def subtract(a, b):
    return a - b

print(subtract(20, 8))
05
Default parameter

Create a greeting function with a default name.

  1. Identify the required inputs and output.
  2. Define the function using def.
  3. Write the required logic inside the indented body.
  4. Call the function and inspect the result.
def greet(name="Student"):
    print("Hello", name)

greet()
greet("Anu")
06
Keyword arguments

Call a function with keyword arguments in a different order.

  1. Identify the required inputs and output.
  2. Define the function using def.
  3. Write the required logic inside the indented body.
  4. Call the function and inspect the result.
def student(name, age):
    print(name, age)

student(age=22, name="Ravi")
07
Average of marks

Return the average of a list of marks.

  1. Identify the required inputs and output.
  2. Define the function using def.
  3. Write the required logic inside the indented body.
  4. Call the function and inspect the result.
def average(marks):
    return sum(marks) / len(marks)

print(average([80, 90, 70]))
08
Maximum of three

Return the largest of three numbers.

  1. Identify the required inputs and output.
  2. Define the function using def.
  3. Write the required logic inside the indented body.
  4. Call the function and inspect the result.
def maximum(a, b, c):
    return max(a, b, c)

print(maximum(10, 45, 22))
09
Even or odd

Return Even or Odd.

  1. Identify the required inputs and output.
  2. Define the function using def.
  3. Write the required logic inside the indented body.
  4. Call the function and inspect the result.
def even_odd(n):
    if n % 2 == 0:
        return "Even"
    return "Odd"

print(even_odd(14))
10
Positive, negative or zero

Classify a number.

  1. Identify the required inputs and output.
  2. Define the function using def.
  3. Write the required logic inside the indented body.
  4. Call the function and inspect the result.
def classify(n):
    if n > 0:
        return "Positive"
    elif n < 0:
        return "Negative"
    return "Zero"

print(classify(-5))
11
Return multiple values

Return sum, difference and product.

  1. Identify the required inputs and output.
  2. Define the function using def.
  3. Write the required logic inside the indented body.
  4. Call the function and inspect the result.
def calculate(a, b):
    return a + b, a - b, a * b

s, d, p = calculate(10, 5)
print(s, d, p)
12
String length

Return the length of a string.

  1. Identify the required inputs and output.
  2. Define the function using def.
  3. Write the required logic inside the indented body.
  4. Call the function and inspect the result.
def string_length(text):
    return len(text)

print(string_length("Python"))
13
Count vowels

Return the number of vowels.

  1. Identify the required inputs and output.
  2. Define the function using def.
  3. Write the required logic inside the indented body.
  4. Call the function and inspect the result.
def count_vowels(text):
    count = 0
    for ch in text.lower():
        if ch in "aeiou":
            count += 1
    return count

print(count_vowels("Programming"))
14
Reverse string

Return a reversed string.

  1. Identify the required inputs and output.
  2. Define the function using def.
  3. Write the required logic inside the indented body.
  4. Call the function and inspect the result.
def reverse_text(text):
    return text[::-1]

print(reverse_text("Python"))
15
List total

Return the total of a list.

  1. Identify the required inputs and output.
  2. Define the function using def.
  3. Write the required logic inside the indented body.
  4. Call the function and inspect the result.
def total(values):
    return sum(values)

print(total([10, 20, 30, 40]))
16
Filter even numbers

Return only even numbers from a list.

  1. Identify the required inputs and output.
  2. Define the function using def.
  3. Write the required logic inside the indented body.
  4. Call the function and inspect the result.
def get_evens(numbers):
    return [n for n in numbers if n % 2 == 0]

print(get_evens([1,2,3,4,5,6]))
17
Use *args

Add any number of numeric arguments.

  1. Identify the required inputs and output.
  2. Define the function using def.
  3. Write the required logic inside the indented body.
  4. Call the function and inspect the result.
def total(*numbers):
    return sum(numbers)

print(total(10, 20, 30, 40))
18
Use **kwargs

Print all key-value pairs supplied to a function.

  1. Identify the required inputs and output.
  2. Define the function using def.
  3. Write the required logic inside the indented body.
  4. Call the function and inspect the result.
def show_profile(**details):
    for key, value in details.items():
        print(key, value)

show_profile(name="Ravi", age=22, city="Hyderabad")
19
Local variable

Create and use a local variable.

  1. Identify the required inputs and output.
  2. Define the function using def.
  3. Write the required logic inside the indented body.
  4. Call the function and inspect the result.
def show():
    message = "Local variable"
    print(message)

show()
20
Global variable

Read a global variable inside a function.

  1. Identify the required inputs and output.
  2. Define the function using def.
  3. Write the required logic inside the indented body.
  4. Call the function and inspect the result.
x = 100

def show():
    print(x)

show()
21
Modify global variable

Increment a global counter using global.

  1. Identify the required inputs and output.
  2. Define the function using def.
  3. Write the required logic inside the indented body.
  4. Call the function and inspect the result.
count = 0

def increment():
    global count
    count += 1

increment()
increment()
print(count)
22
Nested function

Create an outer function containing an inner function.

  1. Identify the required inputs and output.
  2. Define the function using def.
  3. Write the required logic inside the indented body.
  4. Call the function and inspect the result.
def outer():
    def inner():
        print("Inside inner")
    inner()

outer()
23
nonlocal

Modify an enclosing variable.

  1. Identify the required inputs and output.
  2. Define the function using def.
  3. Write the required logic inside the indented body.
  4. Call the function and inspect the result.
def outer():
    x = 10
    def inner():
        nonlocal x
        x += 5
    inner()
    print(x)

outer()
24
Docstring

Add and display a function docstring.

  1. Identify the required inputs and output.
  2. Define the function using def.
  3. Write the required logic inside the indented body.
  4. Call the function and inspect the result.
def square(n):
    '''Return the square of n.'''
    return n * n

print(square.__doc__)
25
Type hints

Write a typed function that adds two integers.

  1. Identify the required inputs and output.
  2. Define the function using def.
  3. Write the required logic inside the indented body.
  4. Call the function and inspect the result.
def add(a: int, b: int) -> int:
    return a + b

print(add(5, 7))
26
Lambda square

Use lambda to calculate a square.

  1. Identify the required inputs and output.
  2. Define the function using def.
  3. Write the required logic inside the indented body.
  4. Call the function and inspect the result.
square = lambda x: x * x
print(square(6))
27
Lambda addition

Use lambda to add two numbers.

  1. Identify the required inputs and output.
  2. Define the function using def.
  3. Write the required logic inside the indented body.
  4. Call the function and inspect the result.
add = lambda a, b: a + b
print(add(8, 12))
28
Sort with lambda

Sort tuples by their second value.

  1. Identify the required inputs and output.
  2. Define the function using def.
  3. Write the required logic inside the indented body.
  4. Call the function and inspect the result.
students = [("Ravi", 80), ("Anu", 95), ("Kiran", 75)]
students.sort(key=lambda x: x[1])
print(students)
29
Recursive factorial

Calculate factorial using recursion.

  1. Identify the required inputs and output.
  2. Define the function using def.
  3. Write the required logic inside the indented body.
  4. Call the function and inspect the result.
def factorial(n):
    if n == 0:
        return 1
    return n * factorial(n - 1)

print(factorial(5))
30
Recursive countdown

Print n down to 1 using recursion.

  1. Identify the required inputs and output.
  2. Define the function using def.
  3. Write the required logic inside the indented body.
  4. Call the function and inspect the result.
def countdown(n):
    if n == 0:
        return
    print(n)
    countdown(n - 1)

countdown(5)
31
Student result

Return Pass if average is at least 40, otherwise Fail.

  1. Identify the required inputs and output.
  2. Define the function using def.
  3. Write the required logic inside the indented body.
  4. Call the function and inspect the result.
def result(marks):
    average = sum(marks) / len(marks)
    if average >= 40:
        return "Pass"
    return "Fail"

print(result([70, 65, 80]))

31 Theory Questions with Answers

Useful for revision, exams and Python interviews.

A function is a reusable block of code designed to perform a specific task.
They reduce repetition and improve organization, readability, testing and reuse.
The def keyword defines a normal Python function.
A function call executes a function, for example greet().
A parameter is a variable in a function definition that receives an argument.
An argument is an actual value supplied when a function is called.
An argument matched to a parameter according to its position.
An argument supplied using the parameter name, such as age=22.
A parameter with a predefined value used when the caller omits that argument.
*args collects extra positional arguments into a tuple.
**kwargs collects extra keyword arguments into a dictionary.
return sends a value back to the caller and ends the current function execution.
print displays information; return provides a result that can be stored or reused.
The function returns None when it finishes without an explicit return value.
Yes. Python commonly packs multiple returned values into a tuple.
Scope is the region of a program where a variable name can be accessed.
A variable created inside a function and normally accessible only within that function.
A variable defined outside functions that can be read from broader program scope.
It allows a function to assign to a global variable.
Python generally searches Local, Enclosing, Global and Built-in scopes.
It lets a nested function modify a variable in an enclosing function scope.
A string used as the first statement in a function to document its purpose.
Annotations documenting intended parameter and return types.
A small anonymous function written using lambda, normally containing one expression.
For short, simple operations where a named def function would be unnecessarily verbose.
Recursion is when a function calls itself.
A condition that stops further recursive calls.
Without a proper stopping condition, calls can continue until Python reaches its recursion limit.
Yes. Python functions can accept objects of many data types.
It means the same function can be called repeatedly with different inputs.
Keep a function focused, use descriptive names, document important behavior and return reusable results.