Python Constants
A constant is a value that should stay the same. ALL_CAPS names mark constants in Python.
A constant at the top
Caps letters mark the value as fixed.
PI = 3.14
print(PI)Use the constant
The program reads PI like any variable.
PI = 3.14
radius = 2
area = PI * radius * radius
print(area)Caps names can still change
Python still allows the change. Good code chooses not to change it.
MAX_LIVES = 3
MAX_LIVES = 4
print(MAX_LIVES)Example
PI = 3.14
radius = 5
area = PI * radius * radius
print("Radius:", radius)
print("Area:", area)Key points
- Constant: a value that is meant to stay the same
- Use ALL_CAPS names for constants, like PI or MAX_SIZE
- Treat a constant as read-only once you set it
- Put constants near the top of the file
In this example, PI is set at the top of the file. Its caps name marks it as a constant. The radius is set to 5. Python works out the area with PI. The print lines show the radius and the area.
Note
Python has no true constants, so the caps name is only a promise.
The math module is a maths toolbox you will meet later.
It offers a ready-made pi value.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
Which name follows the constant naming habit?