Functions and Modules in Python
Part A: Functions in Python
Introduction
A function is a reusable block of code that performs a specific task.
Functions help:
Reduce code repetition
Improve readability
Simplify debugging
Promote code reuse
Example without Function
length = 10
width = 5
area = length * width
print(area)
length = 20
width = 8
area = length * width
print(area)
Notice the repeated code.
Example with Function
def calculate_area(length, width):
area = length * width
return area
print(calculate_area(10,5))
print(calculate_area(20,8))
Defining a Function
Syntax:
def function_name(parameters):
statements
Example:
def greet():
print("Welcome to Python Programming")
Calling the function:
greet()
Output:
Welcome to Python Programming
Function Parameters and Arguments
Parameters
Variables specified in a function definition.
def greet(name):
print("Hello", name)
Arguments
Actual values passed to a function.
greet("Emma")
Output:
Hello Emma
Multiple Parameters
def add_numbers(a, b):
print(a + b)
add_numbers(5, 7)
Output:
12
Return Statement
A return statement sends a value back to the calling program.
def square(number):
return number ** 2
result = square(4)
print(result)
Output:
16
Functions Returning Multiple Values
def calculate(a, b):
sum_value = a + b
product = a * b
return sum_value, product
s, p = calculate(5, 4)
print(s)
print(p)
Output:
20
Default Parameters
def country(name="Kenya"):
print(name)
country()
country("Rwanda")
Output:
Kenya
Rwanda
Keyword Arguments
def student(name, age):
print(name, age)
student(age=20, name="John")
Variable Scope
Local Variables
Accessible only inside a function.
def test():
x = 10
print(x)
test()
Global Variables
Accessible throughout the program.
x = 50
def show():
print(x)
show()
Recursive Functions
A function that calls itself.
def countdown(n):
if n == 0:
print("Done")
else:
print(n)
countdown(n-1)
countdown(5)
Part B: Modules in Python
What is a Module?
A module is a file containing Python code such as:
Functions
Variables
Classes
Modules help organize large programs.
Built-in Modules
Python provides many modules.
Examples:
math
random
statistics
datetime
Importing Modules
Import Entire Module
import math
print([Link](25))
Output:
5.0
Import Specific Function
from math import sqrt
print(sqrt(36))
Output:
6.0
Import Using Alias
import math as m
print([Link])
Output:
3.141592653589793
Common Built-in Modules
Math Module
import math
print([Link](5))
print([Link])
Random Module
import random
print([Link](1,10))
Datetime Module
from datetime import datetime
today = [Link]()
print(today)
Creating User-Defined Modules
Create file:
[Link]
def add(a,b):
return a+b
def multiply(a,b):
return a*b
Save the file.
[Link]
import mymath
print([Link](4,5))
print([Link](4,5))
Output:
20
Advantages of Modules
1. Code reusability
2. Easier maintenance
3. Better organization
4. Faster development
5. Collaboration among programmers
Summary
Functions are reusable blocks of code that perform specific tasks, while modules are files containing
reusable Python code. Together they promote code reuse, readability, maintainability, and modular
software development.
Practical Laboratory Activities
Activity 1: Basic Functions
Create functions to:
Calculate area of a rectangle.
Calculate simple interest.
Determine whether a number is even or odd.
Convert Celsius to Fahrenheit.
Activity 2: Student Results System
Write functions to:
Input student marks.
Calculate average marks.
Determine grade.
Display final report.
Activity 3: Banking Application
Develop functions for:
Deposit
Withdraw
Check balance
Transfer funds
Activity 4: Using Built-in Modules
Write a program that:
Uses random to generate a lottery number.
Uses math to calculate square roots.
Uses datetime to display current date and time.
Activity 5: Creating Your Own Module
Create a module called [Link] containing:
add()
subtract()
multiply()
divide()
Import the module into another program and test all functions.
Group Discussion Questions
1. What advantages do functions provide in programming?
2. Differentiate between parameters and arguments.
3. Explain local and global variables with examples.
4. Why are modules important in software development?
5. Compare built-in modules and user-defined modules.
6. What challenges arise when functions are not used in large programs?
Assessment Questions
1. Define a function and explain its benefits.
2. Write a Python function that calculates the area of a circle.
3. Differentiate between local and global scope.
4. Explain the purpose of the return statement.
5. Create and use a user-defined module called geometry.
6. Write a program that uses the random module to simulate rolling a dice.
7. Explain three advantages of modular programming.
Mini Project (2–3 Hours)
Student Record Management System
Requirements:
Use functions extensively.
Store student names and marks.
Calculate averages.
Assign grades.
Create a separate module called [Link].
Import the grading module into the main program.
Generate a final report for all students.