Variables

Constants

Explore how to define and use constants in Python, understanding the convention of naming constants in uppercase to prevent accidental changes. This lesson helps you recognize constant values in your code and apply good programming practices for reliable calculations.

Constant values

Constants are values that a user does not aim to change. Most languages provide a different syntax for them to ensure their value does not get overwritten in the code accidentally. Although Python does not provide a defined syntax for this purpose, it has a common practice of naming constants in uppercase.

Example

For example, suppose we want to create a program that involves the use of pi. Because we know the value of pi does not change during calculations, we can treat it as a constant and name it PI. It is the programmer’s responsibility to not reassign it elsewhere.

PI = 3.14159 print(PI)

Constant values in Python

More constants

Let’s take a look at some other constants below. We can utilize their values during other calculations but they are not meant to be updated.

# a few more constants TAU = 6.283185307 PHI = 1.618033988 print(TAU) print(PHI) tau_squared = TAU * TAU print(tau_squared)

More constant values in Python

On this page

    In This Module