What is a Module in Python?

 

Introduction

A module in Python is like a toolbox full of functions, classes, and variables that you can reuse in your programs. Instead of writing the same code over and over again, you can store it in a module and import it whenever needed. Think of it like ordering pizza instead of making it from scratch every time!

Creating a Module 

A module is just a Python file that contains functions and variables.

Let's create a simple module called mymodule.py:

# mymodule.py

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

pi = 3.14159

This module contains a function greet() and a variable pi. Now, we can import and use it!

Importing a Module

To use a module, simply import it into your script:

import mymodule

print(mymodule.greet("Alice"))  # Hello, Alice! Welcome to Python.
print(mymodule.pi)  # 3.14159

Importing Specific Items 

If you only need specific functions or variables, use:

from mymodule import greet

print(greet("Bob"))  # Hello, Bob! Welcome to Python.

Now, you don’t need to prefix greet with mymodule.

Renaming a Module 

You can rename a module while importing it using as:

import mymodule as mm

print(mm.greet("Charlie"))

Built-in Modules

Python comes with many built-in modules like math, random, and datetime.

import math

print(math.sqrt(25))  # 5.0

Checking Available Functions

Use dir(module_name) to see what a module contains:

import math
print(dir(math))  # Shows all functions inside math module

Summary

Concept Description
Module A Python file containing reusable code
import module_name Imports the entire module
from module import X Imports a specific function/variable
import module as alias Renames a module during import
Built-in Modules Pre-installed Python modules

Modules make Python programming cleaner, reusable, and more efficient

 

Post a Comment

0 Comments