What is an enum in Python?
a) A symbolic name for a set of values
b) A type of loop
c) A variable that stores multiple values
d) A method for sorting data
Answer:
a) A symbolic name for a set of values
Explanation:
An enum (short for enumeration) in Python is a symbolic name for a set of values. Enums are used to define a collection of named values that are constant and can be used as fixed options throughout a program. They help make the code more readable and maintainable by replacing magic numbers or strings with meaningful names.
from enum import Enum
class Direction(Enum):
NORTH = 1
SOUTH = 2
EAST = 3
WEST = 4
# Using the enum
print(Direction.NORTH) # Output: Direction.NORTH
print(Direction.NORTH.value) # Output: 1
In this example, the Direction
enum defines four possible directions with symbolic names. These values can be used in the program to represent directions without using arbitrary numbers or strings.
Enums provide a way to define a set of related constants, improving code clarity and reducing the likelihood of errors caused by using incorrect or inconsistent values.