Chapter 4: Functions and Modules

As your programs grow, writing all your code in one long file becomes messy and hard to manage. This is known as "spaghetti code." To solve this, we use Functions and Modules to organize code into smaller, logical, and reusable pieces.

1. What are Functions?

A function is a block of code that only runs when it is called. You can pass data, known as parameters, into a function, and the function can return data as a result. Think of a function as a mini-program that performs one specific task, like calculating a square root or formatting a user's name.

def greet(name):
    return "Hello, " + name + "!"

message = greet("CodeMaster")
print(message)

In this example, def is the keyword to define a function. name is the parameter, and return sends the result back to where the function was called.

2. Why Use Functions?

The primary benefit is DRY—"Don't Repeat Yourself." If you need to perform the same calculation in five different places in your program, you shouldn't copy and paste the code five times. Instead, you write the function once and call it whenever you need it.

3. Modules: Reusing Code Across Files

A Module is simply a file containing Python code. By organizing your functions into different files, you can import them into your main script. Python comes with a massive "Standard Library" of modules ready for you to use immediately.

import math

# Using the math module to calculate the square root
print(math.sqrt(16))

4. Scope: Global vs. Local

Variables defined inside a function are "local" to that function, meaning they cannot be accessed outside of it. Variables defined outside are "global" and can be accessed anywhere. Understanding scope is essential for preventing data conflicts in larger projects.

Common Beginner Mistakes

Try It Yourself

  1. Define a function called calculate_area(length, width) that returns the area of a rectangle.
  2. Import the random module and use it to print a random number between 1 and 10.

Default Arguments

Functions can have default values for their parameters, which are used whenever the caller doesn't provide one. This makes functions more flexible without forcing every call to pass every argument.

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

greet("Asha")              # Hello, Asha!
greet("Rahul", "Welcome")  # Welcome, Rahul!

Importing Modules

A module is simply a Python file containing reusable code. Python ships with a huge standard library, so you rarely have to write everything from scratch. To use one, just import it.

import math
print(math.sqrt(64))   # 8.0

from random import randint
print(randint(1, 10))  # a random number between 1 and 10

You can also write your own modules — any .py file can be imported into another by using its filename (without the .py extension) as the module name.