Fix the Enum Bug
Intermediate · Fix the bug · from Python Enums: Type-Safe Constants for Cleaner Code
From the lesson: Python Enums: Type-Safe Constants for Cleaner Code
Imagine you're building a card game. You need to represent the four suits: hearts, diamonds, clubs, and spades. You could use plain strings like "hearts", but what happens when someone types "Hearts" or "hart"? Your code breaks silently.
Read the lessonThis code tries to look up a role from a user-submitted string, but it crashes. Fix the code so it correctly converts the string "admin" into the matching Role enum member and prints its name. Don't change the Role definition.
from enum import Enum
class Role(Enum):
ADMIN = 'admin'
EDITOR = 'editor'
VIEWER = 'viewer'
# Bug: This crashes! Fix it.
user_input = 'admin'
role = Role[user_input]
print(role.name)
More Enum exercises
- Create a Traffic Light EnumIntermediate
- Predict the Enum OutputIntermediate
- HTTP Status Enum with MethodsIntermediate
- Build a Permission SystemAdvanced
All Python exercises · 50 practice problems · Standard Library Essentials quiz