Python Modules

A module in Python is just a file that contains code (functions, variables, or classes) that you can reuse in other programs. It helps keep your code organized and avoids rewriting the same logic again and again. Python itself comes with many built‑in modules like math and random.
  • Key Concept: Organizing code into separate files (.py) to make it manageable and reusable.

Create a Module

Creating a module is as simple as saving a Python file. If you write a few functions in a file named calculator.py, that file becomes a module named calculator. To use these functions in another script, you use the import keyword. This tells Python to go look for that file and make its contents available to you. It connects your current program to the external code you wrote previously.
Example
Step 1: Save this code as pizza_shop.py:
def make_pizza(size, topping):
  return f"Making a {size} inch pizza with {topping}!"
Step 2: In a new file (e.g., main.py), import and use it:
import pizza_shop

order = pizza_shop.make_pizza(12, "pepperoni")
print(order) # Output: Making a 12 inch pizza with pepperoni!

Using the Math Module

The math module is one of the most popular, providing access to mathematical functions defined by the C standard. It allows you to perform complex calculations—like square roots, trigonometry, and logarithms—without writing the complex logic yourself. You simply import it and pass your numbers to its functions.
import math

# Calculate the square root
root = math.sqrt(25)
print(f"The square root is: {root}") # Output: The square root is: 5.0

# Find the ceiling (round up to nearest integer)
up = math.ceil(4.2)
print(f"Rounded up: {up}") # Output: Rounded up: 5

Using the Random Module

The random module is used effectively whenever you need the computer to make a choice or generate data unpredictably. It is widely used in games (like rolling dice), simulations, or picking a random winner from a list. It uses a “pseudo-random” number generator, which means the numbers appear random to humans but are actually calculated by a predictable algorithm starting from a “seed”.
import random

# Generate a random float between 0.0 and 1.0
prob = random.random()
print(f"Random probability: {prob}")

# Pick a random element from a list
snacks = ["Apple", "Banana", "Cookie"]
choice = random.choice(snacks)
print(f"I chose: {choice}") # Output: I chose: Banana (example output)

Different Ways to Import

Python allows multiple ways to import modules:
  • import module → imports the whole module.
  • import module as alias → gives a short name.
  • from module import function → imports only what you need.
import math
import math as m
from math import sqrt

print(math.pi)   # full import
print(m.e)       # alias import
print(sqrt(16))  # specific import

The dir() Function

When you import a module, you might not know exactly what functions or variables are inside it. The built-in dir() function is like a flashlight that lets you look inside a module. It returns a sorted list of strings containing the names of all the functions, variables, and classes defined in that module. This is incredibly useful for debugging or exploring new modules without opening their source code.
import math

# List everything inside the math module
content = dir(math)
print(content[0:5])  # Output might look like: ['__doc__', '__loader__', '__name__', '__package__', '__spec__']

The __name__ Variable

Sometimes you want a file to act as a module (imported by others) and as a standalone script (run directly). The variable __name__ helps you distinguish between these two behaviors. When you run a file directly, Python sets __name__ to "__main__". If the file is imported, __name__ is set to the name of the module. This allows you to write test code that only runs when you execute the file specifically, not when you import it.
# In a file called 'greetings.py'
def say_hi():
  print("Hello!")

if __name__ == "__main__":
  # This only runs if you type 'python greetings.py' in the terminal
  # It will NOT run if you type 'import greetings' elsewhere
  say_hi()

Organizing Modules with Packages

A package is a collection of modules stored in folders with an __init__.py file. It helps organize large projects into smaller parts.

Example structure:

Game/               <-- Package Folder
  __init__.py
  graphics.py     <-- Module
  sound.py        <-- Module

Usage:

from Game import sound

Built‑in vs External Modules

  • Built‑in modules come with Python (like os, math , random ).
  • External modules are created by others and can be installed using pip. This distinction helps you know whether you need to install something extra.
import os       # built-in
import requests # external (install with pip)
Post a comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top