Write a Python Program to Represent enum

Python is a high-level programming language that supports many features to help developers write efficient and concise code.

One of these features is the enum module, which allows you to define and use enumerated constants in your Python code.

In this tutorial, we will learn how to represent an enum in Python.


An enum is a data type that contains a set of predefined constants.

Enumerations are often used to represent sets of related values, such as the days of the week, the months of the year, or the suits in a deck of cards.

In Python, enums are defined using the enum module, which provides a Enum base class that you can subclass to define your own enums.

Here’s an example:

from enum import Enum

class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3

In this example, we define an enum called Color that contains three constants: RED, GREEN, and BLUE.

Each constant is assigned a unique integer value.

To use an enum in your code, you can refer to its constants by name, just like you would with any other attribute.

Here’s an example:

print(Color.RED)   # Output: Color.RED
print(Color.GREEN) # Output: Color.GREEN
print(Color.BLUE)  # Output: Color.BLUE

You can also compare enum constants using the == operator.

Here’s an example:

if Color.RED == Color.GREEN:
    print("They are the same color")
else:
    print("They are different colors")

# Output: They are different colors

Another useful feature of enums is that you can iterate over their constants using a for loop.

Here’s an example:

for color in Color:
    print(color)

# Output:
# Color.RED
# Color.GREEN
# Color.BLUE

Enums can also have methods and properties, just like classes.

Here’s an example:

from enum import Enum

class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3

    def rgb(self):
        if self == Color.RED:
            return (255, 0, 0)
        elif self == Color.GREEN:
            return (0, 255, 0)
        elif self == Color.BLUE:
            return (0, 0, 255)
        else:
            raise ValueError("Invalid color")

print(Color.RED.rgb()) # Output: (255, 0, 0)

In this example, we define a method called rgb() that returns the RGB values of each color.

We can then call this method on any of the enum constants.


In conclusion, enums are a useful feature of Python that can help you write more efficient and readable code.

By defining an enum, you can create a set of related constants and use them throughout your code.

The enum module provides a simple and intuitive way to define enums in Python, making it easy to get started with this powerful feature.