PCEP Control Flow, Loops, Lists and Logic Practice Question
A developer is writing a function that takes a list of numbers and returns the sum of all even numbers. Which two code snippets correctly implement this function? (Select two.)
⚠ Common exam trap
Python Institute often tests the distinction between returning a filtered list versus returning the sum of filtered values, and the trap here is that candidates may confuse list comprehensions (which produce a list) with generator expressions or accumulator logic that produce a single numeric result.
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
✓
def sum_even(nums): total=0; for n in nums: if n%2==0: total+=n; return total
It initializes a total variable to 0, iterates over each number in the list, checks if it is even using the modulo operator (n % 2 == 0), and adds the number to the total. This correctly accumulates the sum of all even numbers and returns the final total.
Answer analysis
Option-by-option breakdown
For each option: why learners choose it and why it is or isn't the right answer here.
- ✗
def sum_even(nums): return [n for n in nums if n%2==0]
Why it's wrong here
Returns a list, not the sum.
- ✗
def sum_even(nums): total=0; for i in range(len(nums)): if nums[i]%2==0: total+=nums[i]*2; return total
Why it's wrong here
Multiplies each even number by 2, resulting in double the sum.
- ✓
def sum_even(nums): total=0; for n in nums: if n%2==0: total+=n; return total
Why this is correct
Correct: loop adds evens to total.
- ✗
def sum_even(nums): total=0; for n in nums: if n%2==1: total+=n; return total
Why it's wrong here
Sums odd numbers instead.
- ✓
def sum_even(nums): return sum(n for n in nums if n%2==0)
Why this is correct
Correct: generator expression sums evens.
Go deeper
Related to this question
About these practice questions
This PCEP question is part of Courseiva's 498-question bank — original exam-style content with full explanations and wrong-answer analysis, never real exam questions or exam 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.