Courseiva
Question 99 of 498
Control Flow, Loops, Lists and LogichardMultiple ChoiceObjective-mapped

PCEP Control Flow, Loops, Lists and Logic Practice Question

A developer is implementing a toggle switch feature. The variable flag starts as False. Which code snippet correctly toggles the flag and performs an action based on the new value each time the code is run? (Assume action1 is performed when flag is True, action2 when False.)

⚠ Common exam trap

Python Institute often tests the order of operations in toggle-and-check patterns, where candidates mistakenly perform the action based on the old flag value instead of the new one after toggling.

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

flag = not flag; if flag: action1() else: action2()

It first toggles the flag using `flag = not flag`, which flips the boolean value from False to True (or vice versa). Then it uses a conditional `if flag:` to check the new value and calls `action1()` when True or `action2()` when False, exactly matching the requirement to act on the new state each time the code runs.

Answer analysis

Option-by-option breakdown

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

  • flag = not flag; if flag: action1() else: action2()

    Why this is correct

    Correctly toggles then uses new value.

  • if not flag: flag = True; action1() else: flag = False; action2()

    Why it's wrong here

    Checks old value before toggling.

  • if flag: flag = False; action1() else: flag = True; action2()

    Why it's wrong here

    Checks old value; toggles after condition.

  • flag = not flag; if flag: action2() else: action1()

    Why it's wrong here

    Toggles first but actions are swapped.

About these practice questions

Courseiva creates original exam-style practice questions with explanations and wrong-answer analysis. It does not publish real exam questions, exam dumps, or protected exam content. Learn why practice questions differ from exam dumps →

How Courseiva writes practice questions · Editorial policy

Last reviewed: Jun 30, 2026

Question Discussion

Share a tip, memory trick, or ask about the reasoning behind this question. Do not post real exam questions, leaked content, braindumps, or copyrighted exam material. Comments are moderated and may be removed without notice.

Loading comments…

Sign in to join the discussion.

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.