Salvatore Lopiparo

Software Engineer

Super Simple Python – Constants

A constant is a value in your code that doesn’t change during execution. They are best used in places that share values throughout your code, or when someone may change their mind about the value itself.

An example of this would be for some text that you wanted to display in multiple locations throughout your program. Normally, you would just copy the the text everywhere it would be used. That means you need to do a lot of extra typing (or copy-paste a bunch). Even worse, if you need to change the value of it, you will have to find all of the occurrences in your code!

import some_modules

class MyClass:
# A bunch of methods here...
    def do_something(self):
        # ... some code
        print("This is my awesome message!")
        # ... more code

    def do_something_else(self):
        # ... some code
        print("This is my awesome message!")
        # ... more code

There is an easier way!

Constants are identified by being in all caps with underscores between words, and are usually put at the top of your .py file just after the imports. If we replace the strings throughout the code that will be the same value with our constant, we can quickly and easily adjust the message as we like!

import some_modules

INFO_MESSAGE = "This is my awesome message!"

class MyClass:
    # A bunch of methods here...
    def do_something(self):
        # ... some code
        print(INFO_MESSAGE)
        # ... more code

    def do_something_else(self):
        # ... some code
        print(INFO_MESSAGE)
        # ... more code

Now in this example, we only need to change INFO_MESSAGE to update our code. This also works well for values that will never change, due to the nature of the value. For example, we may use a short approximation of pi as 3.14. That way, we don’t have to remember the value of pi each time we use it:

import some_modules

INFO_MESSAGE = "We're using pi!"
PI = 3.14

def get_circumference(radius):
    print(INFO_MESSAGE)
    circumference = 2 * PI * radius
    return circumference

def get_area(radius):
    print(INFO_MESSAGE)
    area = PI * PI * radius
    return area