Constants and variables are used to store data values in programming. A variable usually refers to a value that can change over time. A constant is a type of variable whose value cannot be changed during program execution.
There are only six built-in constants available in Python, they are False, True, None, Not Implemented, Ellipsis(...) and __debug__. Apart from these constants, Python does not have any built-in data types to store constant values.
The following demonstrates an example of constants -
False = 100
SyntaxError: cannot assign to False
False is a built-in constant in Python, used to store the Boolean value false. Assigning any value to it is illegal and will raise a SyntaxError.
But in the PEP 8 standard, constants are in uppercase. This helps the user know that it is a constant value. If we encounter any all-caps variables, by convention rather than rule, we should not change their values. Let's look at an example.
π is a mathematical constant, approximately equal to 3.14159. Let us declare the value of the constant π in Python.
# declare constants PI = 3.14159 print(PI)
3.14
In the example above, the mathematical constant pi is declared using all uppercase letters.
As mentioned in the Constants section of PEP 8, we should use uppercase letters and underscores to separate words.
# declare constants LUMINOUS_EFFICACY = 683 VALUE_A = 100 COLOR = 'RED' print(LUMINOUS_EFFICACY) print(VALUE_A) print(COLOR)
683 100 RED
As we can see, constants are also created exactly like variables. Both variables and constants follow similar naming rules, the only difference is that constants only use uppercase letters.
Normally, in Python, constants are declared in modules. Let's take an example and create constants.
Declare constants in a separate file and name the file with a .py extension.
Constants.py file
# declare constants SPEED_OF_LIGHT_IN_VACUUM = 299792458 PI = 3.141592653589793 LUMINOUS_EFFICACY = 683 VALUE = 20
Example.py file
import Constants print(Constants.VALUE) print(Constants.SPEED_OF_LIGHT_IN_VACUUM) print(Constants.PI)
20 299792458 3.141592653589793
In the above example, we created the Constants.py file, called the Constants module. Then, we declared some constant values. After that, we create another python file which is an Example.py file and in this file we import the Constant module using the import keyword. Finally, access the constant value.
The purpose of using uppercase letters is to indicate that the current name is considered a constant. But it doesn't actually prevent the reallocation of constant values.
The above is the detailed content of How to create a constant in Python?. For more information, please follow other related articles on the PHP Chinese website!