Loops: for and while

Repeating a block a known number of times or while a condition holds: the range covered, early exit, nested loops, the infinite loop and the off-by-one error.

  • 29 cards
  • 7 topics
  • Free

The outline, topic by topic

Each topic is weighted the way the exam weighs it.

  1. Concepts
  2. Questions
  3. Sort and link
  4. The numbers
  5. Scenarios
  6. Understand
  7. Line by line

A few cards from the deck

  • Counted loop (for): what is it?

    Show the answer

    A loop whose number of passes is set before it starts: it goes through a range or a collection, item by item.

    for i in range(5): makes exactly 5 passes, with i equal to 0, 1, 2, 3 then 4.

  • What does this program print?

    ```python
    for i in range(1, 5):
    print(i, end=" ")
    `

    • 1 2 3 4
    • 1 2 3 4 5
    • 0 1 2 3 4
    • 2 3 4 5
    Show the answer

    1 2 3 4

    range(1, 5) starts at 1 included and stops before 5: four values. The end bound is always excluded.

  • Each pass through the block of a loop is called an ….

    Show the answer

    Each pass through the block of a loop is called an iteration.

    To iterate is to repeat: the loop for i in range(5): makes five iterations.