Python Modules
In Python, a module is a file containing Python definitions and statements. The file name is the module name with the suffix .py
appended. Modules allow you to logically organize your Python code and reuse it in different programs.
Creating a Module
Save the following code in a file named mymodule.py
:
# mymodule.py
def greet(name):
return f"Hello, {name}!"
def add(x, y):
return x + y
Using a Module
Create a new Python script (e.g., main.py
) in the same directory and use the module:
# main.py
import mymodule
# Using functions from the module
print(mymodule.greet("Alice"))
result = mymodule.add(3, 4)
print(f"The sum is: {result}")
In this example, the main.py
script imports the mymodule
module using the import
statement. Once imported, functions from the module can be used by prefixing them with the module name (e.g., mymodule.greet()
).
Importing Specific Functions
You can import specific functions from a module using the from
keyword:
# main.py
from mymodule import greet, add
# Using functions directly
print(greet("Bob"))
result = add(5, 6)
print(f"The sum is: {result}")
In this example, only the greet
and add
functions are imported directly into the script.
Renaming Modules
You can use the as
keyword to provide a different name for the imported module:
# main.py
import mymodule as mm
# Using functions with the new module name
print(mm.greet("Charlie"))
result = mm.add(7, 8)
print(f"The sum is: {result}")
Executing Modules as Scripts
A module can be executed as a standalone script if you include the following code at the end of the module:
# mymodule.py
def greet(name):
return f"Hello, {name}!"
def add(x, y):
return x + y
if __name__ == "__main__":
# Code to be executed when the module is run as a script
print("Executing mymodule as a script!")
If you run mymodule.py
as the main program, the code under if __name__ == "__main__":
will be executed.
Modules provide a way to organize code, encourage code reuse, and make code more modular and readable. They are a fundamental concept in Python programming.