LevelJar Sign in

Python course / Foundations

Loops

Repeat work with while and for, and walk a sequence while keeping totals, positions and flags straight. Loops are where beginners lose the most time, usually to a stop condition that never fires or a total started in the wrong place.

  • while
  • for
  • range
  • break and continue
  • enumerate
  • zip
  • running totals
  • flags

Start this module

Runs in your browser. Start straight away; create an account when you want your progress kept.

a running total and a position
readings = [4, 7, 7, 2, 9]

total = 0
highest = readings[0]
for position, value in enumerate(readings, start=1):
    total += value
    if value > highest:
        highest = value
    print(f"reading {position}: {value}")

print("total:", total)
print("highest:", highest)
reading 1: 4
reading 2: 7
reading 3: 7
reading 4: 2
reading 5: 9
total: 29
highest: 9

What you will learn

The lessons in this module

  • while
  • Loops that never end
  • for over a string
  • range
  • Steps and counting down
  • Running totals
  • Biggest and smallest
  • break
  • continue
  • Controlling the step yourself
  • Nested loops
  • for with else
  • enumerate
  • zip
  • Asking until the answer is valid
  • Reading until a stop word
  • Reading in the condition
  • Backwards and by position
  • Building text in a loop
  • Several results in one pass
  • Watching a loop run
  • Remembering the previous item
  • Flags that stay set
  • Module review: receipt reader

Ready when you are

Start this module

Previous: Conditions and branching. Next: Lists. All modules are on the course page.