DEV Community

Shahrouz Nikseresht
Shahrouz Nikseresht

Posted on

Python Modules and Imports Explained Simply

Modules help organize code by splitting it into separate files. They make programs easier to manage and allow code reuse.

What is a module?

A module is a Python file (.py) containing functions, variables, or classes.

For example, create a file named math_utils.py:

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

def multiply(a, b):
    return a * b

pi = 3.14159
Enter fullscreen mode Exit fullscreen mode

This file is now a module.

Importing modules

Use import to load a module.

import math_utils

result = math_utils.add(5, 3)
print(result)  # 8

print(math_utils.pi)  # 3.14159
Enter fullscreen mode Exit fullscreen mode

Import specific items:

from math_utils import add, pi

print(add(10, 20))  # 30
print(pi)          # 3.14159
Enter fullscreen mode Exit fullscreen mode

Import everything (not recommended for large modules):

from math_utils import *

print(multiply(4, 5))  # 20
Enter fullscreen mode Exit fullscreen mode

Using built-in modules

Python has many built-in modules.

Random module:

import random

print(random.randint(1, 10))  # Random number between 1 and 10
print(random.choice(["apple", "banana", "cherry"]))  # Random item
Enter fullscreen mode Exit fullscreen mode

Math module:

import math

print(math.sqrt(16))   # 4.0
print(math.pi)         # 3.141592653589793
Enter fullscreen mode Exit fullscreen mode

Aliasing for shorter names

Give a module a shorter name with as:

import random as rnd

print(rnd.randint(1, 100))
Enter fullscreen mode Exit fullscreen mode

Simple examples

Create a greeting module greet.py:

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

def goodbye(name):
    return f"Goodbye, {name}!"
Enter fullscreen mode Exit fullscreen mode

Use it in main file:

from greet import hello, goodbye

print(hello("Alex"))
print(goodbye("Sam"))
Enter fullscreen mode Exit fullscreen mode

Important notes

  • The module file must be in the same folder or in Python's path.
  • Use descriptive module names (lowercase, underscores).
  • Avoid from module import * in larger programs (can cause name conflicts).
  • Modules are loaded only once per program run.

Quick summary

  • Modules are separate .py files with reusable code.
  • Import with import module or from module import item.
  • Use as for aliases.
  • Built-in modules like random and math provide extra functionality.
  • Organize code into modules for better structure.

Practice creating and importing small modules. They are essential for building larger Python programs.

Top comments (0)