Decisions and loops

How programs choose what to do and repeat work: conditions, for and while loops, and loops inside loops.

About 7 hours of study

Learning objectives

Lessons

  1. 1

    Decisions with if

    Compare values and let the program choose a path with if, elif and else.

  2. 2

    Repeating with for loops

    Run the same lines many times with for and range(), and watch the loop variable change.

  3. 3

    Repeating with while

    Repeat while a condition holds, stop early with break, and avoid loops that never end.

  4. 4

    Nested loops

    Put a loop inside a loop to build grids, combine choices, and see how break affects only the inner loop.

Module practice

Module quiz

1. marks = 95. Which grade does this give? if marks >= 40: C, elif marks >= 80: A
2. What is True and not False?
3. How many numbers does range(2, 10, 3) give?
4. When is a while loop a better choice than a for loop?
5. An outer loop runs 5 times, and an inner loop 4 times. How many times does the inner body run?
6. What is wrong with while n > 0: print(n)?

‹ First programsStrings and lists ›