Editor

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 lesson

Refactor 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 average

1. 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([]))

import logging
# Refactor this function to use logging instead of print
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 average
print(process_scores([85, 92, 78, 90]))
print(process_scores([]))

More Logging exercises

All Python exercises · 50 practice problems · Error Handling quiz