In Python, a module is a file containing Python definitions and statements. The file name is the module name with the suffix `.py`. Modules allow you to organize Python code into reusable units.
Here's an explanation with examples:
1. Creating a Module:
Suppose you have a file named `my_module.py`:
```python
# my_module.py
def greet(name):
print(f"Hello, {name}!")
def multiply(a, b):
return a * b
```
2. Using a Module:
Now you can use this module in another Python script or interactive session:
```python
# main_script.py
import my_module
my_module.greet("Alice") # Outputs: Hello, Alice!
result = my_module.multiply(3, 5)
print(result) # Outputs: 15
```
3. Importing Specific Functions:
You can import specific functions from a module:
```python
# main_script.py
from my_module import greet, multiply
greet("Bob") # Outputs: Hello, Bob!
result = multiply(2, 4)
print(result) # Outputs: 8
```
4. Module Aliases:
You can use aliases for module names to make them shorter:
```python
# main_script.py
import my_module as mm
mm.greet("Charlie") # Outputs: Hello, Charlie!
result = mm.multiply(4, 6)
print(result) # Outputs: 24
```
5. Executing Modules as Scripts:
A module can also be executed as a standalone script:
```python
# my_script_module.py
if __name__ == "__main__":
print("This module is being run as a script.")
```
If you run `python my_script_module.py` from the command line, the code inside the `if __name__ == "__main__":` block will be executed.
6. Built-in Modules:
Python comes with a variety of built-in modules. For example, the `math` module:
```python
import math
result = math.sqrt(25)
print(result) # Outputs: 5.0
```
These modules provide additional functionality and can be imported and used in your scripts.
Modules help in organizing code, promoting reusability, and keeping related code together. They are an essential part of building modular and maintainable Python programs.
0 Comments