131.3 Constants and naming conventions
Learn how to define values that do not change, and how to name variables consistently for readable, maintainable code.
What is a constant?
A constant is a value that does not change while the program runs. Using constants makes code more readable, easier to maintain, and helps prevent accidental changes to important values.
Constants are often used for:
Screen dimensions
Player speed
Configuration values
Limits or thresholds
Declaring constants
Python does not have true constants, but programmers use uppercase variable names to signal that a value should not be changed.
SET SCREEN_WIDTH TO 800
SET SCREEN_HEIGHT TO 600
SET MAX_HEALTH TO 100
Even though Python doesn’t enforce it, treating these as fixed values is part of good practice.
Why use constants?
In this example below, the player width should always be half the screen width.
Without constants:
player_x = 400
screen_width = 400 # Mistake! Should be 800, but the value was reused incorrectly
With constants:
player_x = SCREEN_WIDTH // 2
Benefits:
Makes code self-documenting
Reduces “magic numbers” (unexplained hard-coded values)
Simplifies future updates — just change the constant in one place
Naming conventions
To keep code readable, follow these standard naming styles:
Constants: ALL_CAPS with underscores Example:
MAX_SPEED
,DEFAULT_FONT_SIZE
Variables (Python):
snake_case
Example:user_score
,player_position
Class names (Python):
CamelCase
Example:GameScreen
,PlayerStats
Booleans: Use names that start with
is_
,has_
, orcan_
Example:is_visible
,has_lives_left
,can_jump
Reserved words
Avoid using keywords reserved by the programming language. These include:
if
,else
,for
,while
class
,def
,True
,False
These words have special meanings and will cause syntax errors if used as variable names.
Key concepts
A constant is a named value that does not change during execution.
Using named constants improves clarity and maintainability.
Naming conventions help make code consistent and professional.
Reserved words should not be used as variable names.
Last updated
Was this helpful?