Modules in Python

Introduction to Modules

A module is a group of statements that perform a specific task. This approach, also called divide and conquer, breaks a large task into smaller manageable modules.

What is a Module in Python?

A module is a Python file (.py) containing functions, variables, or classes. You can reuse the code by importing the module into other files.

Defining and Calling a Module

Step 1: Create a Module

# mymodule.py

def greet(name):
    return f"Hello, {name}!"

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

Step 2: Use the Module

# main.py

import mymodule

message = mymodule.greet("Alice")
print(message)  # Output: Hello, Alice!

result = mymodule.add(3, 4)
print(result)   # Output: 7

Other Ways to Import

from mymodule import greet, add
print(greet("Bob"))
print(add(2, 5))

import mymodule as mm
print(mm.greet("Eve"))

Summary of Module Syntax

Task Syntax Example
Create modulemymodule.py
Import wholeimport mymodule
Import specificfrom mymodule import greet
Rename on importimport mymodule as mm
Use functionmymodule.greet("Alice")

Local Variables

A local variable is defined inside a function and only exists there.

Example:

def greet():
    message = "Hello, world!"
    print(message)

greet()
print(message)  # Error: message is not defined

Why Use Local Variables?

Local vs Global Variables

message = "Global message"

def greet():
    message = "Local message"
    print(message)

greet()         # Output: Local message
print(message)  # Output: Global message
Term Description Scope
Local VariableDefined inside a functionOnly inside the function
Global VariableDefined outside all functionsAccessible anywhere in the file

Accessing Global Variables

message = "Hello from global scope"

def greet():
    print(message)

greet()
print(message)

Modifying Global Variable Inside Function

counter = 0

def increment():
    counter += 1  # Error: UnboundLocalError

increment()

Correct Way Using global Keyword

counter = 0

def increment():
    global counter
    counter += 1

increment()
print(counter)  # Output: 1

Passing Variables as Arguments

Example:

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

greet("Alice")
greet("Bob")

Using Variable as Argument

user_name = "Eve"

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

greet(user_name)  # Output: Hello, Eve

Better than using global:

count = 10

def increment(value):
    return value + 1

count = increment(count)
print(count)  # Output: 11

Tip: These practices help write modular, reusable, and testable code.