Welcome to our tutorial on Python modules! Modules are a fundamental part of Python that allow you to organize your code into manageable, reusable pieces. In this guide, we'll explore the basics of modules, how to create them, and how to use them effectively.
What are Modules?
A module in Python is a file containing Python code. These files have a .py
extension and can be imported into other Python scripts. Modules help in organizing your code into logical sections, making it easier to manage and reuse.
Creating a Module
To create a module, simply write your Python code in a file with a .py
extension. For example, let's create a module named math_utils.py
:
# math_utils.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b
Importing Modules
To use the functions from math_utils.py
, you need to import the module in your script:
# main.py
import math_utils
result = math_utils.add(5, 3)
print("The sum is:", result)
Standard Libraries
Python comes with a vast collection of standard libraries that provide a wide range of functionalities. Some popular standard libraries include math
, datetime
, and os
.
import math
print("Pi:", math.pi)
Third-Party Modules
You can also install third-party modules using pip
, Python's package manager. For example, to install the requests
module, run:
pip install requests
Then, you can import and use it in your script:
import requests
response = requests.get("https://api.github.com")
print(response.status_code)
Conclusion
Understanding Python modules is crucial for writing efficient and maintainable code. By organizing your code into modules, you can create reusable pieces that can be easily shared and extended.
For more information on Python modules, check out our comprehensive guide on Python Module Development.