Skip to content

Python defines constant

  • by

You can’t defines constant in Python because there is no strict concept of constant as variables. In another programming language, the term constant refers to names representing values that don’t change during a program’s execution.

To indicate to programmers that a variable is a constant, one usually writes it in upper case:

CONST_NAME = "Name"

You can then use the MY_CONSTANT variable throughout your program, knowing that its value will not change.

Python defines constant examples

Simple example code.

MY_CONSTANT = 100
FLAG_CONST = "GLOBAL_CONSTANT"

print(MY_CONSTANT)
print(FLAG_CONST)

Output:

Python defines constant

Define a constant inside function

you can simply declare the constant as all caps, e.g.:

MY_CONSTANT = "one"

If you want that this constant never changes, you can hook into attribute access and do tricks, but a simpler approach is to declare a function:

def MY_CONSTANT():
    return "one"

Do comment if you have any doubts or suggestions on this Python basic topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading