1. Creating a Simple Module:
Consider a simple module named my_module.py
:
# my_module.py
def greet(name):
return f"Hello, {name}!"
def add_numbers(a, b):
return a + b
2. Using the Module in Another Script:
You can use this module in another Python script by importing it.
# main.py
import my_module
# Using functions from the module
result_greet = my_module.greet("Alice")
result_sum = my_module.add_numbers(3, 4)
print(result_greet)
print(result_sum)
3. Importing Specific Functions:
You can import specific functions from a module to avoid using the module name as a prefix.
# Importing specific functions
from my_module import greet, add_numbers
result_greet = greet("Bob")
result_sum = add_numbers(5, 7)
print(result_greet)
print(result_sum)
4. Alias for Modules:
You can use aliases when importing modules to make the code more concise.
# Alias for a module
import my_module as mm
result_greet = mm.greet("Charlie")
result_sum = mm.add_numbers(2, 8)
print(result_greet)
print(result_sum)
5. Importing Specific Functions with Aliases:
Combining aliasing with specific function imports.
# Importing specific functions with aliases
from my_module import greet as my_greet, add_numbers as my_add
result_greet = my_greet("David")
result_sum = my_add(6, 9)
print(result_greet)
print(result_sum)
6. Executing Module as a Script:
You can check if a module is being run as the main program and execute certain code accordingly.
# Executing module as a script
if __name__ == "__main__":
print("This is executed when the module is run as a script.")
7. Conclusion:
Creating and using modules in Python is a fundamental aspect of organizing and structuring code. By modularizing your code, you enhance its readability, reusability, and maintainability. Whether you’re working on a small script or a large-scale project, understanding how to create and use modules is crucial for effective Python programming.
In the next sections, we’ll explore more advanced topics and practical applications of modules in Python.