TOPIC 4: Functions & Code Documentation

Site: Learning Management System
Course: Edo College ICT Club Programme
Book: TOPIC 4: Functions & Code Documentation
Printed by: Guest user
Date: Tuesday, 14 April 2026, 8:43 AM

1. What is a Function?

A function is a reusable block of code that performs a specific task. Functions allow you to organize your code, break down complex tasks, and avoid repetition. By using functions, you can make your code more modular, readable, and maintainable.

Why Functions?

  • Code Reusability: Once a function is defined, it can be reused throughout the program, reducing duplication of code.
  • Readability: Functions break down complex tasks into smaller, understandable pieces of code.
  • Modularity: Functions allow for organizing code into logical parts, making debugging and testing easier.

Syntax for Defining a Function:

To define a function in Python, we use the def keyword, followed by the function name, parentheses (for parameters), and a colon. The code block inside the function is indented.

def function_name(parameters):
    # code block
    return result
  • def: This keyword is used to define a function.
  • function_name: The name of the function (use descriptive names to make it clear what the function does).
  • parameters: The values (inputs) passed to the function when it is called. These can be optional.
  • code block: The set of statements that define what the function does.
  • return: The return statement is used to send a result back to the caller.

Example 1: Simple Function

This is a simple function that prints a greeting message:

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

greet()  # Output: Hello, World!

Explanation:

  • The function greet() is defined with no parameters and simply prints "Hello, World!" when called.
  • Calling a function: You invoke a function by writing its name followed by parentheses: greet().

Example 2: Function with Parameters

A function can take parameters (inputs), which allow it to be more flexible.

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

result = add(5, 3)
print(result)  # Output: 8

Explanation:

  • The function add(a, b) takes two parameters, a and b, and returns their sum.
  • The function is called with arguments 5 and 3, and the result is stored in result and printed.

2. Function Parameters and Return Values

Functions can accept parameters and return values.

  • Parameters: These are values passed into the function when called. Parameters allow the function to operate on different data each time it is called.
  • Return Values: Functions can send a value back to the caller using the return keyword. The return statement allows you to output a result from the function.

Example 1: Function with Multiple Parameters

def multiply(x, y):
    return x * y

result = multiply(4, 5)
print(result)  # Output: 20

Explanation:

  • The function multiply(x, y) takes two parameters, x and y, multiplies them, and returns the result.
  • The function is called with the arguments 4 and 5, and the result is stored in result.

Example 2: Function with Default Parameters

Functions can have default values for parameters, which are used if no value is passed when calling the function.

def greet(name="Guest"):
    print(f"Hello, {name}!")

greet("Alice")  # Output: Hello, Alice!
greet()         # Output: Hello, Guest!

Explanation:

  • The function greet(name="Guest") has a default value for the name parameter.
  • If no argument is passed to greet(), it defaults to "Guest". If an argument is passed (e.g., "Alice"), it uses that value.

3. Documentation (Docstrings)

Docstrings are used to describe the functionality of a function, class, or module. They help other developers (or your future self) understand what the code does.

  • Docstrings are enclosed in triple quotes ("""docstring""").
  • The docstring should immediately follow the function header.

Example 1: Basic Docstring

def greet(name):
    """
    This function greets the person with their name.
    """
    print(f"Hello, {name}!")

greet("Alice")

Explanation:

  • The function greet(name) includes a docstring explaining that the function greets a person by their name.
  • Calling help(greet) will display the docstring, helping you understand what the function does.

Example 2: Detailed Docstring for a Function

A more detailed docstring can include information about the parameters and the return value of the function.

def add(a, b):
    """
    This function adds two numbers a and b.
    
    Parameters:
        a (int): The first number.
        b (int): The second number.
    
    Returns:
        int: The sum of a and b.
    """
    return a + b

Explanation:

  • The docstring explains the function’s purpose, its parameters, and its return value.
  • This is particularly useful for understanding the function's input-output behavior.

4. Built-in Functions in Python

Python has many built-in functions that are available for use without needing to define them. These functions perform common tasks and are essential for Python programming.

Common Built-in Functions:

print(): Outputs data to the console.

print("Hello, World!")

len(): Returns the length of an object (e.g., string, list).

my_list = [1, 2, 3]

print(len(my_list))  # Output: 3

type(): Returns the type of an object.

x = 5
print(type(x))  # Output: <class 'int'>

str(): Converts an object to a string.

x = 100

print(str(x))  # Output: '100'

int(): Converts an object to an integer.

x = "10"
print(int(x))  # Output: 10

sum(): Returns the sum of elements in an iterable (like a list).

numbers = [1, 2, 3]
print(sum(numbers))  # Output: 6

1. 

max(): Returns the largest item in an iterable.

numbers = [1, 2, 3, 4]
print(max(numbers))  # Output: 4

min(): Returns the smallest item in an iterable.

numbers = [1, 2, 3, 4]
print(min(numbers))  # Output: 1

5. Modules in Python

A module in Python is a file containing Python code (functions, classes, and variables). It allows you to organize your code and reuse it across different programs.

  • Importing a Module: To use a module, you can import it using the import statement.
import math
print(math.sqrt(16))  # Output: 4.0
  • Import Specific Functions: You can import specific functions from a module:
from math import sqrt
print(sqrt(16))  # Output: 4.0

Using the datetime Module

  • Converting String to Date: To convert the task deadline from a string to a datetime object, we use the datetime.strptime() method.
from datetime import datetime
deadline = "2025-03-22"
deadline_date = datetime.strptime(deadline, "%Y-%m-%d")
print(deadline_date)  # Output: 2025-03-22 00:00:00
  • Comparing Dates: To check if a task's deadline is approaching, we can compare dates like this:
from datetime import datetime
deadline_date = datetime(2025, 3, 22)
today = datetime.now()

if (deadline_date - today).days <= 2:
    print("Task is due soon!")