Python Constants

A constant is a variable whose value cannot change once it has been assigned.

Sometimes, you may want to store values in variables, but won't want to change these values throughout the execution of the program.

To do this in other programming languages, you can use constants. Constants are like variables, but their values don’t change as the program executes.

The bad news is that Python doesn’t support constants.

To work around this, you can use capital letters to name a variable. This indicates that the variable should be treated as a constant. For example:

LIST_SIZE = 50

When encountering variables like these, you should not change their values. These variables are constant by convention, not by rules.

But, we can define constant in Python using Touple, because a tuple is a list that cannot change. Python refers to a value that cannot change as immutable. So, by definition, a tuple is an immutable list.

We can define only one element In Touple so it works like a constant.

Example:

LIST_SIZE = (100,)
print(LIST_SIZE) #It Returns (100,), But We Need Only 100, So For That Access Value As Following
print(LIST_SIZE[0])

If we want to change the value of touple, it may return an error. For example:

LIST_SIZE[0] = 200

The above code will give an error like this:

#TypeError: 'tuple' object does not support item assignment

So, like constants, we can't change the value of touple. Therefore, we can use touple as a constant In Python.

Summary

Python doesn’t have built-in constant types.

Using Touple, we made a constant variable and used it by Index 0.


Similar Articles