Exercises
Enums
3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.
Exercise 1Passed
Replace the loose strings with an enum, and print the value of NORTH.
Python
# define Direction with NORTH and SOUTH
print(Direction.NORTH.value)Subclass Enum and assign each member a value.
from enum import Enum
class Direction(Enum):
NORTH = "north"
SOUTH = "south"
print(Direction.NORTH.value)Exercise 2Passed
Print the names of every member, in order.
Python
from enum import Enum
class Status(Enum):
PENDING = 1
ACTIVE = 2
DONE = 3
# print ['PENDING', 'ACTIVE', 'DONE']
An enum class is iterable, and each member has a name.
from enum import Enum
class Status(Enum):
PENDING = 1
ACTIVE = 2
DONE = 3
print([s.name for s in Status])Exercise 3Passed
Make the members compare equal to their string values.
Python
from enum import Enum
class Mode(Enum):
FAST = "fast"
print(Mode.FAST == "fast")There is a variant whose members really are strings.
from enum import StrEnum
class Mode(StrEnum):
FAST = "fast"
print(Mode.FAST == "fast")