Python Modules and Import Statement Explained
Introduction
In the previous post, we learned about Python Exception Handling. Now let’s understand how Python allows us to organize and reuse code using Modules.
What is a Module in Python?
A module is simply a Python file that contains functions, variables, or classes.
Instead of writing all code in one file, we divide it into multiple files for better structure.
---Why Use Modules?
- Improves code organization
- Reusability of code
- Makes debugging easier
- Used in real-world projects
Importing Built-in Modules
Python provides many built-in modules like math.
import math
print(math.sqrt(16))
print(math.factorial(5))
Import Specific Function
from math import sqrt
print(sqrt(25))
Using Alias Name
import math as m
print(m.pi)
print(m.pow(2,3))
Creating Your Own Module
Step 1: Create a file called my_module.py
def greet(name):
return "Hello " + name
def add(a, b):
return a + b
Step 2: Use it in another file
import my_module
print(my_module.greet("Ayush"))
print(my_module.add(5, 3))
Understanding __name__ Variable
if __name__ == "__main__":
print("This file is running directly")
This ensures some code runs only when the file is executed directly.
---Popular Built-in Modules
- math → Mathematical operations
- random → Random number generation
- datetime → Date and time handling
- os → Operating system operations
What You Learned in This Post
- What is a module
- How to import modules
- Using alias names
- Creating custom modules
- Understanding __name__
What’s Next?
Now that you understand modules, it’s time to learn about Python Virtual Environments and why they are important in real projects.
Next Post: Python Virtual Environment Explained for Beginners
---About the Author
Ayush Gupta
MSc AI/ML Student | Python & Machine Learning Enthusiast
Comments
Post a Comment