Lesson 4: Functions and Modular Programming | Coding Class Series
Lesson 4: Functions and Modular Programming | Coding Class Series
Introduction
Welcome to Lesson 4!
In this lesson, we will learn about functions – reusable blocks of code – and how to organize your program into modules. Functions make your code cleaner, easier to read, and maintainable.
What is a Function?
A function is a block of code that performs a specific task. You can call it whenever you need to perform that task.
Example in Python:
def greet(name):
print(f"Hello, {name}!")
greet("Alice") # Output: Hello, Alice!
greet("Bob") # Output: Hello, Bob!
Explanation:
def greet(name):→ defines a function namedgreetwith a parametername.print(f"Hello, {name}!")→ code inside the function.greet("Alice")→ calls the function with argument"Alice".
Benefits of Functions
- Reusability: Write once, use many times.
- Readability: Makes code organized and easier to understand.
- Debugging: Easy to test and fix small blocks of code.
Modular Programming
Modular programming is the practice of splitting your code into multiple files or modules. Each module has a specific purpose, making your program scalable and easier to maintain.
Example:
math_utils.py→ contains functions for math operationsmain.py→ calls functions frommath_utils.py
# math_utils.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b
# main.py
from math_utils import add, subtract
print(add(5, 3)) # Output: 8
print(subtract(5, 3)) # Output: 2
Practice Exercises
- Write a function to calculate the factorial of a number.
- Create a function to check if a string is a palindrome.
- Write a module
string_utils.pycontaining functions:reverse_string(),count_vowels(). - Import the module in another file and test all the functions.