CodeBlanks Logo Icon CodeBlanks

Constants

Learn class-level constants.

Class constants

A constant is a value that does not change. In Python constants are named in uppercase: MAX_USERS = 100. When defined in a class body, it becomes a class constant.

Example: class Config:\n MAX_USERS = 100\n DEFAULT_LANG = "en". Accessed as Config.MAX_USERS. Python constants can technically be changed, but the uppercase name signals that you should not. This is a convention.

Using constants

Constants remove magic numbers. Writing if users > Config.MAX_USERS is more readable than if users > 100; the meaning of the number is in its name.

Class constants are accessed via the class: Config.MAX_USERS, Config.DEFAULT_LANG. They can be accessed via an instance too, but the class name is more common. When the value changes, you update it in one place; this eases maintenance.

Practice Define the Config constants

Define a class named Config. Add the constants MAX_USERS = 100 and DEFAULT_LANG = "en" in the body. Then call print(Config.MAX_USERS) and print(Config.DEFAULT_LANG).

Starter code

main.py
# Define the Config class

Sample solution

main.py
# Define the Config class
class Config:
    MAX_USERS = 100
    DEFAULT_LANG = "en"

print(Config.MAX_USERS)
print(Config.DEFAULT_LANG)

Expected output

100
en

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the constant concepts

Term Meaning
MAX_USERS Uppercase name
100 Constant value
Config.MAX_USERS Access via class

2 How is a class constant named?

  • lowercase
  • camelCase
  • UPPER_SNAKE_CASE Correct answer
  • PascalCase

Explanation: Constants use uppercase letters and underscores.

3 Complete the constant declaration

Question
class Config:
    ____ = 100
Answer
class Config:
    MAX_USERS = 100

Explanation: Constants use uppercase letters and underscores.

All lessons in Intermediate