Python - Constants
What are Constants?
Constants are values that should not be changed during the execution of a program. Python does not have built-in constant types like some other languages (e.g., Java or C++), but developers use naming conventions and design patterns to simulate constants.
Why Use Constants?
- To make your code more readable and maintainable.
- To prevent accidental changes of critical values.
- To indicate that a particular variable is fixed throughout the program.
How to Define Constants?
There is no native const keyword in Python. However, developers typically use all-uppercase variable names to signal that the value should not be changed.
python
PI = 3.14159 # This is a constant
GRAVITY = 9.8 # Acceleration due to gravity
print("Pi:", PI)
print("Gravity:", GRAVITY)
When to Use Constants?
- For values that should not change like mathematical values (e.g., Pi).
- Configuration values like API keys, file paths, etc.
- Limits and thresholds used in your program.
Using Constants in Classes
You can define constants in a class or module to group them together:
python
class Constants:
PI = 3.14159
GRAVITY = 9.8
SPEED_OF_LIGHT = 299792458 # in m/s
print(Constants.SPEED_OF_LIGHT)
Pros and Cons
Pros:
- Improves code readability.
- Protects critical values from being changed.
- Easy to update in one place if needed.
Cons:
- No enforcement in Python – constants can still be changed if someone modifies the code.
- Can lead to misuse if not properly documented.