Saturday, May 16, 2026

Python Tutorial for Beignners: Modules & Packages

When programs grow bigger, writing everything in a single file can become messy and hard to manage. Multiple functions, classes, and static variables can make code confusing, difficult to read, and hard to reuse.

Python provides modules and packages to help organize code in a clean, reusable way.

Read: Python OOPs Concept

What is Python Modules and Packages?

Module: A module is simply a single Python file (.py) that contains functions, classes, variables, or runnable code. 

Example: mymath.py

#mymath.py
def add(x1, x2):
return x1+x2
def multiply(x1, x2): return x1*x2

Now we can use this module or file in another file using import keyword.

import mymath
print(mymath.add(5, 6))
print()
print(mymath.multiply(9, 3)

You can also give a aliases (nick name) name to the moudle like: import mymath as mt and access using the nick name: print(mt.add(5, 6))

We can also import specific function
from mymath import add
print(add(2, 3))

Package: A package is a folder containing multiple modules, along with a special __init__.py file. Packages help organize modules into a directory structure. This allows large projects to remain clean and modular.

Example:

Myfolder
    __init__.py
    mymath.py
    mycode.py

Note: __init__.py can be empty or contain initialization code. It tells Python that this folder should be treated as a package

Using a module from Package

from Myfolder import mymath
print(mymath.add(20, 30))
print()
print(mymath.multiply(10, 10)) 

Python built-in Module

Python has many built-in modules like math, random, etc.
import math
print(math.sqrt(25))
print()
print(math.pi)
import random
print(random.randint(1, 5)

Tasks:

  1. Create a module with a function to find square of a number.
  2. Import that module in another file and use it.
  3. Create a package with two modules.
  4. Use math module to calculate square root.

Mini Project: Generate Random Password

import random
import string

def gen_password(length):
    new = (string.ascii_letters + string.digits)
    password = "".join(random.choice(new) for i in range(length))
    return(password)
# in place of "i" we can also use "_" because we don't need this value # this is just a placeholder
print(gen_password(7))

Conclusion

In this chapter, I explained modules and packages. They help make your programs shorter, more organized, and reusable. If you want to learn Python effectively, understanding modules and packages is very important, because they allow you to structure your code in a clean and maintainable way.

Practice Your Code Below

🐍 Python Playground

No comments:

Post a Comment

Featured Post

Python OOPs Advanced: Class Variables and Instance Variables

We have learned how to create classes and objects . Now, we will explore class variables and instance variables in Python, including how the...