โ† 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 this code? x = 5 while x > 0: x -= 1 if x == 2: break else: print('loop ended') print('after')

    Answer: after

    x reaches 2 and break fires, skipping the else, so only 'after' is printed.

  2. The `else` block of a loop is executed when:

    Answer: No break statement terminated the loop

    The else block runs whenever the loop exits without a break, regardless of whether the body ran zero or many times.

  3. What does this code print? primes = [2, 3, 5] for p in primes: if p > 4: break else: print('all small') print('checked')

    Answer: checked

    p==5 satisfies p>4, triggering break, so the else is skipped and only 'checked' is printed.

  4. Can an `else` block on a loop be combined with a `try/except` inside the loop body?

    Answer: Yes, they are independent constructs

    A try/except inside the loop body and a loop else block are completely independent; catching an exception does not affect the else clause.

  5. What is the output? for i in range(1, 6): if i % 2 == 0: print(i) else: print('done')

    Answer: 2 4 done

    The loop prints even numbers 2 and 4, then the else block prints 'done' since no break occurred.

  6. Which of the following is TRUE about the loop `else` clause?

    Answer: It runs after every complete loop, whether the iterable was empty or not

    The else clause runs after any complete loop exit (including an empty iterable) as long as break was not used.

  7. What is the output of this code? for i in range(3): for j in range(3): if i + j == 4: break else: print('outer done')

    Answer: outer done

    The outer else only skips if the outer loop hits break; inner breaks don't affect it, so after the outer loop completes, 'outer done' prints once.