Courseiva
Control Flow, Loops, Lists and LogichardMultiple ChoiceObjective-mapped

PCEP Control Flow, Loops, Lists and Logic Practice Question

A team observes that the following code prints 'Found' even when the item is not in the list. Code: for item in mylist: if item == target: print('Found'); break; else: print('Not found'). Which modification ensures it correctly prints 'Not found' only if the item is not present?

⚠ Common exam trap

Python Institute often tests the for-else construct by presenting code where the else is incorrectly indented under the if, leading candidates to think the else belongs to the if statement, when in fact the intended behavior requires the else to be aligned with the for.

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

Align the else with the for statement (for-else construct)

The original code uses a for-else construct where the else block executes after the loop completes normally (i.e., without a break). However, the code has a syntax error: the else is incorrectly indented as part of the if statement, causing it to execute on every iteration when the condition is false. Aligning the else with the for statement (for-else construct) ensures the else block runs only if the loop finishes without hitting a break, which occurs when the item is not found.

Answer analysis

Option-by-option breakdown

For each option: why learners choose it and why it is or isn't the right answer here.

  • Move else inside the if block

    Why it's wrong here

    This would not change the logic; else still prints for each non-matching item.

  • Replace break with continue

    Why it's wrong here

    continue does not terminate loop; else clause will always execute.

  • Use a flag variable to track found status

    Why it's wrong here

    This works but is not the most Pythonic; for-else is preferred.

  • Align the else with the for statement (for-else construct)

    Why this is correct

    Correct: for-else executes else only if no break occurred.

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 →

How Courseiva writes practice questions · Editorial policy

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.