Python Modules
A module in Python is a file containing Python code (functions, classes, and variables) that you can reuse in other programs. Modules help organize code into smaller, manageable, and reusable components.
Create and Using a Module
1. Create a Module
To create the model for save your python code in a .py file. for example, create a file named my_module.py:
# my_module.py def greet(name): return f"Hello, {name}!" def add(a, b): return a + b
2. Import the Module
To import a module in Python, you can use the import keyword.
import my_module print(my_module.greet("Gokul")) # Hello, Gokul! print(my_module.add(8, 7)) # 15
Output
Hello, Gokul! 15
3. Import specific functions, variables, or classes
In Python modules, the from ... import ... statement allows you to import specific functions, variables, or classes directly from a module instead of importing the entire module. This approach can make your code cleaner and more focused, as you only include the elements you need.
from my_module import greet print(greet("Krish")) # Hello, Krish!
Output
Hello, Krish!
4. Built-in Modules
Python comes with a rich library of built-in modules that provide functionality out of the box. These modules are part of Python's standard library and don't require additional installation. The math function provides mathematical functions.
# importing built-in module math import math # using square root(sqrt) function # in math module print(math.sqrt(400)) # 1 * 2 * 3 * 4 * 5 = 120 print(math.factorial(5)) # importing built in module random import random # printing random integer between 0 and 5 print(random.randint(0, 20)) # importing built in module datetime import time # Returns the number of seconds print(time.time())
Output
20.0 120 5 1735890342.719479