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 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.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 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.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}")Write a loop that counts all animals observed during the expedition. Complete the code in the editor:
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 repetitionswhile - repeats as long as a condition is Truebreak - stops the loop, continue - skips one repetitionIn the last lesson of this block Darwin will show you functions - how to wrap code into a reusable tool!