Python Constants
Constants are similar to variables that hold the data which can be referenced, but we cannot change or manipulate the value of the constant during the execution of the program.
Unlike other Programming languages, Python does not have constants. However, we can use the variables themselves as constants.
In Python, any variable you declare in Capital letters (uppercase) can be considered a constant.
PI = 3.14
API_KEY = "a4wasdf83qsffj"
DEFAULT_TIMEOUT = 30
Constants
Like variables, constants consist of two things, a name and an associated value.
The name describes what the constants are all about, and the value is nothing but the information it holds.
Constants are useful in a variety of situations, for example, to store the value of:
- a configuration parameter (e.g., the name of a file),
- a mathematical constant (e.g., math.Pi),
- a unit of measurement (e.g., time.Second).
- an API tokens, API Base URL, etc
- any value that doesn't change often
Constants Best Practices
- Create constant names in all uppercase. For Eg:
USER
- In case of multiple words, separate them by an underscore. For Eg:
EMPLOYEE_STATUS
. - Ensure you have given a meaningful name for constants.
- Constants can be of any length, however, keep it short and meaningful
- It can consist of digits but should not be the first character. Eg:
YEAR_2022_STUDENTS
,AGE_BELOW_30
Let us look at an example to leverage constants.
# PI is a Constant
PI = 3.14
# Read the radius as input from the user
radius = float(input("Enter the radius of a circle: "))
# Calculate the area of a circle
area_of_circle = PI * radius * radius
# Print the area of a circle
print("Area of a circle is:", area_of_circle)
Enter the radius of a circle: 5
Area of a circle is: 78.5
Built-in Constants in Python
Python has few Built-in constants.
According to the Python docs a small number of constants live in the built-in namespace. They are:
-
False
: The false value is of the bool type. Assignments to False are illegal and raise a SyntaxError. It is also an instance ofint
and has a value of0
. -
True
: The true value of the bool type. Assignments to True are illegal and raise a SyntaxError. It is also an instance ofint
and has a value of1
. -
None
: An object frequently used to represent the absence of a value, as when default arguments are not passed to a function. Assignments to None are illegal and raise a SyntaxError. None is the sole instance of the NoneType type