Make decisions and repeat actions with Python.
Conditions and loops
Learning objectives
- Compare values with conditions.
- Use
if,elif, andelse. - Repeat work with
forandwhile. - Avoid infinite loops.
Decisions
battery_percent = 24
if battery_percent < 20:
message = "Return the robot to its charging station."
elif battery_percent < 50:
message = "The robot can continue, but monitor the battery."
else:
message = "The battery level is healthy."
print(message)
The indented block belongs to the condition above it. Comparisons produce True or False.
Repetition
temperatures = [20, 21, 19, 23]
for temperature in temperatures:
print(f"Recorded temperature: {temperature} C")
Use a while loop when the number of repetitions depends on a condition:
countdown = 3
while countdown > 0:
print(countdown)
countdown -= 1
print("Launch!")
The loop must change something that can eventually make its condition false.
Practice
Write a program that examines a list of sensor readings and prints "warning" for readings below 10. Add a counter for the number of warnings.
Checkpoint
Predict how many times each loop runs before executing it. Explain what would happen if countdown -= 1 were removed.
Mini-project
Create a safe robot decision simulator. Given distance readings, print stop when an obstacle is closer than 20 cm and move otherwise. Include at least five readings and report how many stops occurred.