Concept Explanation
As your programs grow from 10 lines to 10,000 lines, keeping everything in a single file becomes impossible. Modules are simply Python files (.py) that contain functions, classes, and variables.
By splitting your code into modules, you make it easier to manage, test, and share. If you write a great math library, you can "import" it into any other project without rewriting a single line of code. Python also comes with a "Standard Library"—a collection of thousands of pre-written modules for everything from web servers to zip file compression.
Syntax or Core Structure
The Three Ways to Import
- Standard Import: Imports the whole module. You must use the module name to access its tools.
import math->math.sqrt(16)
- Specific Import: Imports only what you need. You don't need the module name.
from math import sqrt->sqrt(16)
- Alias Import: Gives the module a shorter nickname.
import pandas as pd->pd.DataFrame()
Code Example #1 (Basic)
Using the built-in random and datetime modules.
import random
from datetime import datetime
# Get a random number
secret_number = random.randint(1, 100)
# Get the current time
now = datetime.now()
print(f"Generated {secret_number} at {now.strftime('%H:%M:%S')}")
Code Example #2 (Intermediate)
Creating your own custom module. Imagine you have a file called calculator.py.
# --- In calculator.py ---
def multiply(a, b):
return a * b
# --- In your main.py ---
import calculator
result = calculator.multiply(10, 5)
print(f"The result is {result}")
Real World Example
When you install a library like Requests or Flask (which we'll cover later), you are essentially downloading professional modules written by other developers and importing them into your project.
# 📦 External Module Usage
# First, you would run: pip install requests
import requests
# This module handles all the complex networking code for you!
response = requests.get("https://api.github.com")
if response.status_code == 200:
print("Success! The internet is working.")
Common Mistakes
- Naming Conflicts: If you name your file
random.py, you will "shadow" the built-in Pythonrandommodule, and yourimport randomcalls will fail or behave strangely. Never name your files the same as standard libraries! - Circular Imports: If
Module AimportsModule B, andModule BimportsModule A, Python will get stuck in a loop and crash. - *Importing Everything ()**: Avoid using
from module import *. It makes it impossible for other developers to know where a function came from (didshow()come from your code or the library?).
Best Practices
- Alphabetic Order: Imports should be at the very top of the file, grouped by (1) Standard Libraries, (2) Third-party Libraries, and (3) Your own modules.
- Use
if __name__ == "__main__":: When writing a module, put your testing code inside this block. It ensures that the test code ONLY runs when you execute the module file directly, and NOT when someone imports it.
Practice Exercises
- Math Explorer: Import the
mathmodule. Use it to calculate the square root of 625 and the value of Pi rounded to 2 decimal places. - The Nickname: Import the
osmodule (which handles file paths) and give it the aliassystem. Print the current directory usingsystem.getcwd(). - Custom Utility: Create a second script file with a function that calculates a person's birth year from their current age. Import it into your main script and call it.