Sunday, June 7, 2020

Assigning value to constant in Python

Assigning value to constant in Python

In Python, constants are usually declared and assigned in a module. Here, the module is a new file containing variables, functions, etc which is imported to the main file. Inside the module, constants are written in all capital letters and underscores separating the words.

Example 3: Declaring and assigning value to a constant

Create a constant.py:
PI = 3.14
GRAVITY = 9.8
Create a main.py:
import constant

print(constant.PI)
print(constant.GRAVITY)
Output
3.14
9.8
In the above program, we create a constant.py module file. Then, we assign the constant value to PI and GRAVITY. After that, we create a main.py file and import the constant module. Finally, we print the constant value.
Note: In reality, we don't use constants in Python. Naming them in all capital letters is a convention to separate them from variables, however, it does not actually prevent reassignment.

No comments:

Post a Comment