HOME HTML EDITOR C JAVA PHP python

Python Modules

A module in Python is simply a file containing Python code (.py) that can define functions, classes, and variables. Modules help you organize large programs into clean, maintainable pieces and reuse code across multiple scripts.

1. Creating & Importing a Custom Module

Suppose you save the following code in a file named mymodule.py:

# File: mymodule.py
def welcome(name):
    return f"Welcome to Expertsjava, {name}!"

site_version = 1.0

Now you can import and use it in another Python file:

import mymodule

print(mymodule.welcome("Ananya"))
print("Version:", mymodule.site_version)

2. Using Aliases (as) & from ... import

You can give a module a shorter alias with as, or import only specific functions/variables directly so you don't need the module prefix every time:

import mymodule as mm
from mymodule import welcome

print(mm.site_version)
print(welcome("Rohan"))

3. Built-in Standard Modules

Python ships with a rich standard library of built-in modules like math and random that are ready to use without extra installation:

import math
import random

print("Square root of 64:", math.sqrt(64))
print("Random number (1-10):", random.randint(1, 10))
Tip: Avoid naming your custom module files after built-in Python modules (such as math.py or random.py), as that can shadow Python's standard library imports.