PCEP Computer Programming and Python Fundamentals Practice Question
A developer writes a Python script that calculates the average of a list of numbers. The script sometimes produces a ZeroDivisionError. Which of the following is the MOST appropriate way to handle this error to keep the script running?
⚠ Common exam trap
Python Institute often tests the distinction between error prevention (e.g., if-checks) and error handling (e.g., try/except), where candidates mistakenly choose a pre-check that only partially addresses the error, while the correct answer uses exception handling to cover all cases.
Answer choices
Why each option matters
Answer the question above first, then reveal the full breakdown to understand why each option is right or wrong.
Correct answer & explanation
✓
Wrap the division in a try/except block and catch ZeroDivisionError, then set the average to 0.
It uses a try/except block to catch the ZeroDivisionError specifically, which is the most robust and Pythonic way to handle runtime errors. This approach keeps the script running by setting the average to 0 when the list is empty, without relying on pre-checks that might miss other causes of division by zero (e.g., if the sum is 0 but the list is not empty). In Python, exception handling is preferred for error-prone operations like division, as it separates normal logic from error handling cleanly.
Answer analysis
Option-by-option breakdown
For each option: why learners choose it and why it is or isn't the right answer here.
- ✗
Check if len(numbers) == 0 before division and skip calculation if true.
Why it's wrong here
Prevents error but requires explicit check; not the most Pythonic way if the list can be modified concurrently.
- ✗
Use an if statement to check if the list is empty and print a warning message.
Why it's wrong here
Prevents error but does not handle the case where the list becomes empty after the check.
- ✗
Remove the last element from the list if it is empty.
Why it's wrong here
Modifies the list arbitrarily; not a correct solution.
- ✓
Wrap the division in a try/except block and catch ZeroDivisionError, then set the average to 0.
Why this is correct
Handles the error gracefully and allows continuation.
Go deeper
Related to this question
About these practice questions
Courseiva writes every PCEP question from scratch — 498 in total, each with an explanation and a wrong-answer breakdown. None are copied from real exams or dumps. Learn why practice questions differ from exam dumps →
JA
Written by Johnson Ajibi, MSc IT Security
Senior Network & Security Engineer · founder of Courseiva
This PCEP practice question is part of Courseiva's free Python Institute certification practice question bank. Courseiva provides original exam-style practice questions with explanations, topic-based practice, mock exams, readiness tracking, and study analytics to help learners prepare for the PCEP exam.