Python Program to Represent enum
In Python, an enum (short for enumeration) is a set of named values that represent a collection of related constants. Enums provide a way to create a fixed set of named values that can be used throughout a program, making code more readable and maintainable.
In Python, enums are defined using the enum module. Once an enum is defined, you can use it to create instances of the named values.
Python Code :
The Below Python program, creates an enumeration using the enum module. Here’s an example of how to create an enum:
import enum
class Color(enum.Enum):
RED = 1
GREEN = 2
BLUE = 3
In this example, we define an enum called Color with three possible values: RED, GREEN, and BLUE. Each value is assigned a numeric value, starting with 1.
Here’s an example of how to use the Color enum in your code:
favorite_color = Color.RED
if favorite_color == Color.RED:
print("Your favorite color is red.")
elif favorite_color == Color.GREEN:
print("Your favorite color is green.")
elif favorite_color == Color.BLUE:
print("Your favorite color is blue.")
else:
print("Your favorite color is something else.")
In this example, we create a variable called favorite_color and set it to Color.RED. We then use an if statement to check which color favorite_color represents, and print a message accordingly.
Using an enum can make your code more readable and less error-prone, because it ensures that you’re only working with values that are defined in the enum.