This answer key contains 4 multiple-choice, 4 fill-in-the-blank, and 4 output-prediction questions for Python Enums, with the exact answer and a short explanation for every question.
The answers are shown in full, so use this page after making an attempt. The practice page is the better first pass.
What is Color.RED?
Answer: An enum member
Why: Enum members are unique objects; the string is stored in .value.
What does this code print?
from enum import Enum
class Color(Enum):
RED = "red"
print(Color.RED.value)Answer: red
Why: The value attribute returns the underlying string.
What does iterating over an Enum yield?
Answer: Its members
Why: Iteration yields the member objects in definition order.
What does Color('green') return?
Answer: The Color.GREEN member
Why: Calling the enum with a value looks up the matching member.
Complete the base class for an enum.
from enum import Enum
class Color(____):
RED = "red"Answer: Enum
Why: Enum is the standard base class for named members.
Complete the attribute that returns the underlying value.
from enum import Enum
class Color(Enum):
RED = "red"
print(Color.RED.____)Answer: value
Why: A member stores its assigned value in .value.
Complete the attribute that returns the member name.
from enum import Enum
class Color(Enum):
RED = "red"
print(Color.RED.____)Answer: name
Why: A member stores its identifier in .name.
Complete the name lookup.
from enum import Enum
class Color(Enum):
RED = "red"
print(Color["____"])Answer: RED
Why: Square brackets look up a member by its name.
What does the program output?
from enum import Enum
class Color(Enum):
RED = "red"
print(Color.RED.name)Answer: RED
Why: The name attribute is the identifier RED.
What appears on the screen?
from enum import Enum
class Color(Enum):
RED = "red"
GREEN = "green"
print(Color("green").value)Answer: green
Why: Lookup by value returns GREEN, whose value is green.
What is printed?
from enum import Enum
class Color(Enum):
RED = "red"
GREEN = "green"
print(len(list(Color)))Answer: 2
Why: There are two members, so the list has length two.
What is the output?
from enum import Enum
class Color(Enum):
RED = "red"
print(Color.RED is Color.RED)Answer: True
Why: Enum members are singletons, so the identity comparison is true.
Try the questions first
Open the practice page for Python Enums and answer the same 12 questions with instant feedback.