Lesson 6 - Loops (for & while)
Learning Objective
Repeat code with for loops over sequences and ranges, and with while loops driven by a condition; use break and continue to control loop flow.
Introduction
Loops allow you to execute the same block of code multiple times without copying and pasting it.
Python provides two primary loop types:
- for loops — used when iterating over a sequence or a known range of values.
- while loops — used when repetition should continue until a condition becomes false.
Loops are fundamental to programming because they let your programs process collections of data, retry operations, monitor sensors, and automate repetitive tasks.
The for Loop
A for loop iterates over each item in a sequence.
Example:
for i in range(5):
print(i)Output:
0
1
2
3
4The loop automatically stops after the last value.
Using range()
range() generates a sequence of numbers.
range(5)Produces:
0, 1, 2, 3, 4range(2, 6)Produces:
2, 3, 4, 5range(0, 10, 2)Produces:
0, 2, 4, 6, 8Iterating Over Lists
A for loop can iterate directly over items in a list.
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)Output:
apple
banana
cherryCode
# loops.py
# for loop over a range
for i in range(5):
print(f"Count: {i}")
# for loop over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"I like {fruit}")
# while loop with a counter
countdown = 3
while countdown > 0:
print(f"Launching in {countdown}...")
countdown -= 1
print("Liftoff!")
# break and continue
for n in range(10):
if n == 3:
continue # skip this iteration
if n == 6:
break # stop the loop entirely
print("n =", n)Expected Output
Click to see expected output
Count: 0
Count: 1
Count: 2
Count: 3
Count: 4
I like apple
I like banana
I like cherry
Launching in 3...
Launching in 2...
Launching in 1...
Liftoff!
n = 0
n = 1
n = 2
n = 4
n = 5The while Loop
A while loop continues running as long as its condition remains true.
Example:
countdown = 3
while countdown > 0:
print(countdown)
countdown -= 1Output:
3
2
1The loop stops when:
countdown > 0becomes false.
Using continue
The continue statement skips the rest of the current iteration and moves directly to the next one.
for n in range(5):
if n == 2:
continue
print(n)Output:
0
1
3
4Notice that 2 is skipped.
Using break
The break statement immediately exits the loop.
for n in range(10):
if n == 4:
break
print(n)Output:
0
1
2
3The loop stops completely once n becomes 4.
Loop Flow Visualization
for n in range(10):When:
n == 3Python executes:
continueand skips printing.
When:
n == 6Python executes:
breakand exits the loop immediately.
This is why the output becomes:
0
1
2
4
5🔧 Under the Hood
Why can a while loop run forever, but a for loop can’t?
A for loop walks through a fixed sequence:
range(5)contains exactly five values.
Once Python reaches the end of that sequence, the loop automatically stops.
A while loop is different:
while condition:Python only checks whether the condition is true or false.
It has no way of knowing whether the condition will ever become false.
For example:
count = 1
while count > 0:
print(count)This loop never changes count, so:
count > 0is always true.
The loop runs forever.
This is called an infinite loop and is one of the most common beginner mistakes.
What continue Does
continueImmediately jumps back to the next iteration.
Any code below it inside the loop is skipped.
What break Does
breakImmediately exits the entire loop.
No further iterations are executed.
Student Challenge
Challenge 1
Write a FizzBuzz program.
For numbers 1 through 30:
- Print
"Fizz"if divisible by 3. - Print
"Buzz"if divisible by 5. - Print
"FizzBuzz"if divisible by both. - Otherwise print the number itself.
Hint
Check the “divisible by both” case first.
If you check:
n % 3 == 0before:
n % 3 == 0 and n % 5 == 0then numbers like 15 will incorrectly print "Fizz" instead of "FizzBuzz".
Click to see solution
# fizzbuzz.py
for n in range(1, 31):
if n % 3 == 0 and n % 5 == 0:
print("FizzBuzz")
elif n % 3 == 0:
print("Fizz")
elif n % 5 == 0:
print("Buzz")
else:
print(n)Challenge 2
Have your BonicBot hop forward repeatedly, checking for obstacles before every hop.
Experiment with:
max_steps = 10and:
distance < 0.8to see how the robot behaves.
Full parameter details for drive_distance() are available in the Python SDK reference.
Hint
max_steps provides a safety limit.
Even if no obstacle is ever detected, the robot will eventually stop.
This is a good practice whenever controlling real hardware.
Click to see solution
# challenge_safe_hops.py
from bonicbot_bridge import BonicBot
with BonicBot(host='192.168.0.188') as bot:
bot.wait_for_data(timeout=3.0)
step_count = 0
max_steps = 5
while step_count < max_steps:
distance = bot.get_min_obstacle_distance()
if distance is not None and distance < 0.5:
print(f"Obstacle at {distance:.2f} m — stopping.")
break
print("Path clear, hopping forward.")
bot.drive_distance(0.2, speed=0.2)
step_count += 1
bot.stop()
print(f"Stopped after {step_count} hop(s).")Reflection Question
The
whileloop above has two ways to stop:breakon an obstacle, orstep_countreachingmax_steps. Why is it safer to have both, rather than relying on the obstacle check alone?
By the end of this lesson, you should be comfortable using for loops, iterating with range(), looping through lists, building condition-based while loops, and controlling execution with break and continue.