While Loops - Python

  1. With nums = [3, 1], which exception does while True: nums.pop() eventually raise?
    Answer: IndexError while True never stops on its own. After both items are removed, pop() is called on an empty list and raises IndexError. StopIteration is wrong: while loops do not raise it. Only iterators do, inside for loops or next().
  2. Starting with n = 1, which loop leaves n equal to 16?
    Answer: while n < 16: n *= 2 Doubling from 1 gives 2, 4, 8, 16. At 16 the test n < 16 is false, so n stays 16. With <=, 16 still passes the test, and n doubles once more to 32.
  3. After n = 10 and c = 0, what is c after while n > 1: n //= 2; c += 1 runs?
    Answer: 3 Both statements after the colon are in the loop body. n goes 10 to 5 to 2 to 1, so c becomes 3. At n = 1 the test n > 1 fails. Getting 4 means looping while n > 0, which would add one more step from 1 to 0.
  4. With i = 0, which loop prints 0, 1 and 2, each on its own line?
    Answer: while i < 3: print(i); i += 1 Printing before adding 1, while i < 3, prints 0, 1 and 2. Putting the increment first shifts the output to 1, 2, 3. Using <= 3 adds an extra pass that prints 3.
  5. In Python, when does the else block attached to a while loop run?
    Answer: When the condition turns false without a break A while loop's else runs when the loop ends because its condition became false. A break skips it. The block is not like finally, so leaving through break does not trigger it. It also runs whether the body executed zero times or many times.

Start this quiz