HTTP Status Enum with Methods
Intermediate · Write the code · 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 lessonCreate an Enum called HTTPStatus with members OK = 200, NOT_FOUND = 404, and SERVER_ERROR = 500. Add a property called is_error that returns True if the value is 400 or above. Print each status and whether it's an error.
from enum import Enum
class HTTPStatus(Enum):
# Define members and is_error property
pass
for status in HTTPStatus:
print(f'{status.name} ({status.value}): error={status.is_error}')
More Enum exercises
- Create a Traffic Light EnumIntermediate
- Predict the Enum OutputIntermediate
- Fix the Enum BugIntermediate
- Build a Permission SystemAdvanced
All Python exercises · 50 practice problems · Standard Library Essentials quiz