Python course Β· Module 1: Python Basics
Loops - Cycles of Nature
In this lesson5
Welcome! 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.
animals = ["Lion", "Elephant", "Giraffe", "Python"]
for animal in animals:
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.
# Print expedition days from 1 to 5
for day in range(1, 6):
print(f"Day {day} of the expedition")
# range(5) generates 0, 1, 2, 3, 4
for i in range(5):
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.
water_supply = 5
while water_supply > 0:
print(f"Water remaining: {water_supply} liters")
water_supply = water_supply - 1 # use up a liter
print("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).
animals = ["Gazelle", "Lion", "Antelope", "Zebra"]
for animal in animals:
if animal == "Lion":
print("Predator! Stopping observation.")
break # exit the loop
print(f"Safe: {animal}")numbers = [1, 2, 3, 4, 5, 6]
for number in numbers:
if number % 2 != 0:
continue # skip odd numbers
print(f"Even number: {number}")Practice
Write a loop that counts all animals observed during the expedition. Run the loops in the editor and add another animal to the list:
Code for this lesson: main.py
# Loops - counting animals during the expedition
animals = ["Lion", "Elephant", "Giraffe", "Zebra", "Python"]
# TODO: use a for loop to display each animal
for animal in animals:
print(f"Observed: {animal}")
# TODO: count how many animals there are (count in the loop)
count = 0
for animal in animals:
count = count + 1
print(f"Observed {count} animals in total")
# TODO: use range() to print 3 expedition days
for day in range(1, 4):
print(f"Day {day} of the expedition")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 repetitionswhile- repeats as long as a condition isTruebreak- 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!
Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. What does the for loop go through in for animal in animals?
2. What numbers will range(1, 6) generate?
3. What does the break statement do in a loop?
Hands-on tasks in the game
- Vertical ordering
Arrange the while loop so that it prints 5, 4, 3, 2, 1 in turn: