Welcome!
Join our coding community
Β© 2024 Ace Coding Academy
Code Examples
Example 1
Using naming convention. By convention, constants are named using ALL_CAPS. This signals to other programmers that these values shouldn't change. Python doesn't enforce constants, but this convention is widely respected.
PI = 3.14159
GRAVITY = 9.8
MAX_CONNECTIONS = 100
Example 2
Constants for configuration. Constants make program configuration explicit and easy to find. Placing them at the top of a file makes them easy to modify if needed. Avoids "magic numbers" or string literals scattered throughout code. "Magic numbers" refer to hardcoded numeric values (or sometimes string literals) that appear directly in the code without explanation or context. They are often used without any clear meaning, making the code harder to understand and maintain. By using a constant, the code becomes more readable and maintainable. If you need to change the value later, you only need to update the constant, rather than searching through the entire codebase for all occurrences of the magic number.
DATABASE_URL = "postgresql://localhost:5432/myapp"
API_KEY = "abc123xyz456"
TIMEOUT_SECONDS = 30
Example 3
Mathematical constants. Well-known mathematical values that never change. Makes formulas more readable and self-documenting. Note: For standard mathematical constants, you can import from the math module.
PI = 3.14159
GOLDEN_RATIO = 1.61803
# Using the constants
circle_area = PI * (radius ** 2)
golden_rectangle_width = height * GOLDEN_RATIO