We use cookies to enhance your experience on the site
CodeWorlds

Loops - Cycles of Nature

Welcome, @name! Nature loves repetition: the sun rises every morning, waves crash on the shore, the herd migrates every year. In programming we also often need to repeat something - check every animal on a list, count expedition days, generate a report every hour. Instead of rewriting the same code many times, we use loops.

The for Loop - Go Through Every Element

The `for` loop goes through the elements of a collection one by one - like an explorer who observes each animal in the herd one after another.

1animals = ["Lion", "Elephant", "Giraffe", "Python"]
2
3for animal in animals:
4    print(f"Observed: {animal}")

Python takes the first element of the list, assigns it to the variable `animal`, and runs the indented block. Then it takes the second element, the third - until the end of the list. Just like with `if`, there is a colon after the header and an indented block.

range() - Repeat a Specific Number of Times

When we want to do something a specific number of times, we use `range()`. This function generates a sequence of numbers.

1# Print expedition days from 1 to 5
2for day in range(1, 6):
3    print(f"Day {day} of the expedition")
4
5# range(5) generates 0, 1, 2, 3, 4
6for i in range(5):
7    print(f"Step {i}")

Remember: `range(1, 6)` gives numbers from 1 to 5 - the upper bound (6) is not included. And `range(5)` starts at 0 and gives 0, 1, 2, 3, 4.

The while Loop - Repeat As Long As the Condition Is Met

The `while` loop repeats code as long as a condition is `True`. We use it when we don't know in advance how many repetitions we'll need.

1water_supply = 5
2
3while water_supply > 0:
4    print(f"💧 Water remaining: {water_supply} liters")
5    water_supply = water_supply - 1   # use up a liter
6
7print("Out of water!")

Python checks the condition before each repetition. As long as `water_supply > 0` is `True`, it runs the block. Very important: inside the loop we must change the condition (here: decrease the water supply), otherwise the loop will never end - this is called an infinite loop.

break and continue - Controlling the Loop

Sometimes we want to stop a loop early (`break`) or skip one repetition and move to the next (`continue`).

1animals = ["Gazelle", "Lion", "Antelope", "Zebra"]
2
3for animal in animals:
4    if animal == "Lion":
5        print("⚠️ Predator! Stopping observation.")
6        break   # exit the loop
7    print(f"Safe: {animal}")
1numbers = [1, 2, 3, 4, 5, 6]
2
3for number in numbers:
4    if number % 2 != 0:
5        continue   # skip odd numbers
6    print(f"Even number: {number}")

Practice

Write a loop that counts all animals observed during the expedition. Complete the code in the editor:

Summary

In this lesson you mastered repeating code:

  • ✅ `for` - goes through elements of a collection (e.g., a list)
  • ✅ `range()` - generates a sequence of numbers for repetitions
  • ✅ `while` - repeats as long as a condition is `True`
  • ✅ `break` - stops the loop, `continue` - skips one repetition
  • ✅ The danger of an infinite loop

In the last lesson of this block Darwin will show you functions - how to wrap code into a reusable tool! 🧰🌴

Go to CodeWorlds