About Lesson
Module in Python
A module is a file containing Python definitions and statements. It can contain functions, classes, variables, and runnable code. In Python, a module allows you to organize your code into separate files for better structure, readability, and maintainability.
Key Concepts:
- Importing a module: To use the code in a module, you can import it using the
import
statement:
Python
import module_name
Alternatively, you can import specific items from a module:
Python
from module_name import function_name
Standard Library: Python provides a large collection of built-in modules as part of the Python Standard Library (e.g., os
, sys
, math
).
Creating a module: Any Python file (with a .py
extension) is a module. For example, mymodule.py
is a module.
Namespaces: Modules create their own namespace, meaning variables and functions inside a module are accessed using module_name.name
.
Example:
Python
# mymodule.py
def greet():
print("Hello from the module!")
# main.py
import mymodule
mymodule.greet() # Outputs: Hello from the module!