โ† All PCEP Flashcard Decks

Using the `else` block in loops Flashcards

7 cards from real PCEP practice questions. Tap to flip, then mark Knew It or Still Learning โ€” missed cards come back until you master them.

Read the first 7 Using the `else` block in loops flashcards as text
  1. What is the output of the following code? ```python for i in range(3): print(i) else: print('Done!') ```

    Answer: 0 1 2 Done!

    The `else` block in a `for` loop executes only if the loop completes its entire iteration without being terminated by a `break` statement. In this case, the loop finishes normally, so 'Done!' is printed after the numbers 0, 1, and 2.

  2. What is the output of the following code? ```python for num in [1, 2, 3, 4]: if num == 3: break print(num) else: print('Finished.') ```

    Answer: 1 2

    The `break` statement terminates the loop when `num` is 3. Because the loop did not complete its full iteration, the `else` block is skipped entirely. Only the numbers before the `break` are printed.

  3. What is the output of this `while` loop? ```python i = 5 while i > 0: i -= 1 if i == 2: continue print(i) else: print('Loop over.') ```

    Answer: 4 3 1 0 Loop over.

    The `continue` statement skips the current iteration but does not terminate the loop. The loop continues until `i` becomes 0, at which point the condition `i > 0` is false. Since the loop completed normally, the `else` block is executed.

  4. Under which circumstance is the `else` block of a loop NOT executed?

    Answer: When a `break` statement is executed.

    The primary purpose of the `else` block in a loop is to run code when the loop finishes its iterations naturally. If the loop is exited prematurely using a `break` statement, the `else` block is skipped.

  5. What will be printed to the console? ```python for char in 'PCEP': print(char) break else: print('End of string') ```

    Answer: P

    The loop starts with the first character 'P' and prints it. Immediately after, the `break` statement is encountered, which terminates the loop. Since the loop was terminated by `break`, the `else` block is not executed.

  6. Consider the following code. What is the output? ```python items = [] for item in items: print(item) else: print('No items found.') ```

    Answer: No items found.

    When a `for` loop is given an empty sequence (like an empty list), it does not execute its body at all. It is considered to have completed 'normally' without any iterations. Therefore, the `else` block is executed.

  7. What is the output of this code snippet? ```python n = 3 while n > 0: n -= 1 print(n) else: if n == 0: print('Loop ended.') ```

    Answer: 2 1 0 Loop ended.

    The `while` loop runs until `n` becomes 0. The loop prints 2, 1, and 0. When `n` is 0, the condition `n > 0` becomes false, and the loop terminates. Since it terminated normally, the `else` block is executed. Inside the `else` block, the condition `n == 0` is true, so 'Loop ended.' is printed.