Modules in Python
Hey there! In this guide, we'll explore modules in Python. Modules are files containing Python code that can define functions, classes, and variables. They allow you to organize your code logically and reuse code across different programs. Let's dive in!
Python Modules​
- Code Organization: Modules help organize code into manageable sections, making it easier to maintain.
- Reusability: You can reuse code in multiple programs without rewriting it.
- Standard Library: Python comes with a standard library of modules that provide useful functions and tools.
1. Creating a Module​
You can create a module by simply creating a new Python file (with a .py
extension) and defining functions or variables in it.
# my_module.py
def greet(name):
return f"Hello, {name}!"
PI = 3.14159
2. Importing a Module​
You can import a module using the import
statement. You can import the entire module or specific functions or variables.
import my_module # Import the entire module
from my_module import greet # Import specific function
print(my_module.PI) # Output: 3.14159
print(greet("Alice")) # Output: Hello, Alice!
3. Importing with Aliases​
You can give a module or function an alias using the as
keyword to simplify its usage.
import my_module as mm
print(mm.PI) # Output: 3.14159
print(mm.greet("Bob")) # Output: Hello, Bob!
4. The __name__
Variable​
The __name__
variable allows you to check if a module is being run as the main program or if it is being imported.
# my_module.py
def greet(name):
return f"Hello, {name}!"
if __name__ == "__main__":
print(greet("Main")) # This code runs only if the module is executed directly
5. Using Standard Library Modules​
Python's standard library provides many built-in modules you can use in your programs.
import math
print(math.sqrt(16)) # Output: 4.0
print(math.pi) # Output: 3.141592653589793