Python Modules
Python modules are files containing Python code that can be imported and used in other Python programs. They allow you to organize and reuse code, making it easier to maintain and collaborate on projects.
A module can define functions, classes, and variables that can be used in other programs. It can also include executable statements that are run when the module is imported. Modules are typically stored in separate .py
files.
Here’s an example of a simple module called my_module.py
:
python
# my_module.py
def greeting(name):
print(f"Hello, {name}!")
def square(x):
return x ** 2
# executable statement
print("This is my_module.py")
To use the functions and variables defined in my_module.py
in another Python program, you can import it using the import
statement:
python
import my_module
my_module.greeting("Alice") # Output: Hello, Alice!
print(my_module.square(5)) # Output: 25
You can also import specific functions or variables from a module:
python
from my_module import greeting, square
greeting("Bob") # Output: Hello, Bob!
print(square(3)) # Output: 9
Python has a large standard library with many built-in modules that provide useful functionality, such as math
for mathematical operations, datetime
for working with dates and times, and random
for generating random numbers. These modules can be imported and used in your programs just like user-defined modules.
Additionally, you can create your own modules by defining functions and classes in separate files and using them in your programs. Modules are an essential part of Python’s modular programming approach, promoting code organization, reusability, and maintainability.