Refactor: Replace print() with Logging
Intermediate · Refactor · from Python Logging: Stop Using print() for Debugging
From the lesson: Python Logging: Stop Using print() for Debugging
Every airplane has a flight recorder - a "black box" that silently records everything that happens during a flight. If something goes wrong, investigators can replay the recording to figure out exactly what happened and when.
Read the lessonRefactor this function to replace all print() debug statements with proper logging calls. Keep the final print() for user output.
Original code:
def process_scores(scores):
print('DEBUG: Received scores:', scores)
if not scores:
print('ERROR: No scores provided')
return None
total = sum(scores)
print('DEBUG: Total =', total)
average = total / len(scores)
print('INFO: Average calculated:', average)
return average1. Set up logging with level=DEBUG, format='%(levelname)s: %(message)s', stream=sys.stdout (import sys), force=True
2. Replace print DEBUGs with logging.debug()
3. Replace print ERROR with logging.error()
4. Replace print INFO with logging.info()
5. Call print(process_scores([85, 92, 78, 90])) and print(process_scores([]))
More Logging exercises
- Predict the Output: Log Level FilteringBeginner
- Add Logging to a FunctionBeginner
- Fix the Bug: Missing MessagesIntermediate
- Build a Login Validator with LoggingIntermediate
All Python exercises · 50 practice problems · Error Handling quiz