Python Modules

What is a Module in Python?

A module in Python is a file containing Python definitions and statements. Modules help organize and reuse code across multiple programs. Python has many built-in modules, and you can also create your own.

1. Using a Built-in Module: math

import math
print(math.sqrt(25))
print(math.pi)

Output:

5.0
3.141592653589793

Explanation:

  • import math loads the math module.
  • math.sqrt(25) returns the square root of 25.
  • math.pi returns the value of π (pi).

2. Importing Specific Functions from a Module

from math import sqrt, pi
print(sqrt(16))
print(pi)

Output:

4.0
3.141592653589793

3. Renaming a Module Using as

import math as m
print(m.factorial(5))

Output:

120

Explanation:

  • math is imported as m, a shorter alias.
  • m.factorial(5) computes 5! (5 factorial).

4. Creating and Importing Your Own Module

File 1: my_module.py

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

File 2: main.py

import my_module
print(my_module.greet("Dharmendra"))

Output:

Hello, Dharmendra!

Explanation:

  • my_module.py contains a custom function.
  • main.py imports and uses that function.

5. Using dir() to List Module Attributes

import math
print(dir(math))

Output:

['_doc_', '_loader_', '_name_', 'acos', 'asin', ..., 'trunc']

Explanation:

  • dir() lists all functions, variables, and attributes inside the module.

6. Using the __name__ Variable in Modules

File: my_module.py

def greet():
   print("Hello from the module!")
if __name__ == "__main__":
   greet()

Explanation:

  • If you run my_module.py directly, greet() will execute.
  • If imported, it won't run automatically—this is a common Python practice.

Summary

FeatureDescription
import module_nameImport entire module
from module import xImport specific functions
import module as aliasImport module with alias
dir(module)View functions and variables in a module
__name__ == "__main__"Code runs only when the module is run directly