Modules in Python: Import, Use, and Create Your Own

If Python were a toolbox, modules would be the individual compartments each holding tools for a specific job.

In this detailed guide, you’ll learn:

  • What modules are and why they’re important
  • How to use built-in modules
  • The difference between import, from ... import, and as
  • How to create your own module from scratch
  • Best practices and common pitfalls

🧠 What Are Modules?

A module is simply a Python file that contains code like variables, functions, or classes that you can reuse across other files.

Python comes with many built-in modules like:

  • math (mathematical functions)
  • random (generate random numbers)
  • datetime (date and time)
  • os (interact with files and the operating system)

You can also create your own.


🔗 Why Use Modules?

  • Avoid repeating the same code
  • Organize your project into logical parts
  • Keep things clean and maintainable
  • Use code written by others (standard library or third-party)

🔄 How to Import a Module

✳️ Import Entire Module

Python
import math

print(math.sqrt(25))  # Output: 5.0

Access with: module_name.function_name


🎯 Import Specific Function

Python
from math import sqrt

print(sqrt(64))  # Output: 8.0

You can use the function directly without prefixing with math.


📛 Give a Module an Alias

Python
import datetime as dt

today = dt.date.today()
print(today)

Shortens long names, makes code more readable.


🔐 Some Common Built-in Modules

ModulePurposeExample Use
mathMath functionsmath.sqrt(), math.pi
randomRandom number generationrandom.randint(), random.choice()
datetimeDate and time handlingdatetime.now()
osFile system interactionos.getcwd(), os.listdir()
sysPython runtime settingssys.argv, sys.exit()
statisticsStats functionsmean(), median()

🧪 Example: Dice Simulator with random

Python
import random

dice = random.randint(1, 6)
print("You rolled:", dice)

🔥 Creating Your Own Module

Step 1: Create a New File

Create a file called helper.py and write:

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

Step 2: Import and Use It

In your main script (e.g., main.py):

Python
import helper

print(helper.greet("Ali"))

Output:

Hello, Ali!


🔎 From Your Module, Import Specific Things

Python
from helper import greet

print(greet("Fatima"))

🧱 Organizing Projects with Modules

Folder structure:

Python
myproject/

├── helper.py
├── math_utils.py
├── main.py

You can import like:

Python
from math_utils import multiply

Just make sure all .py files are in the same folder or properly packaged.


📦 Installing External Modules (Bonus Tip)

Use pip to install 3rd-party modules:

Python
pip install requests

Then:

Python
import requests

response = requests.get("https://pyuniverse.com")
print(response.status_code)

⚠️ Common Mistakes with Modules

MistakeFix
Forgetting .py extensionJust write import mymodule, NOT import mymodule.py
File not in the same folderUse correct relative paths or sys.path for advanced setups
Function not accessibleMake sure it’s not inside if __name__ == "__main__":
Same name as built-in moduleDon’t name your file math.py, random.py, etc.

💌 Stay Updated with PyUniverse

Want Python and AI explained simply straight to your inbox?

Join hundreds of curious learners who get:

  • ✅ Practical Python tips & mini tutorials
  • ✅ New blog posts before anyone else
  • ✅ Downloadable cheat sheets & quick guides
  • ✅ Behind-the-scenes updates from PyUniverse

No spam. No noise. Just useful stuff that helps you grow one email at a time.

🛡️ I respect your privacy. You can unsubscribe anytime.

Leave a Comment