A sensor reading is just a number. A program turns that number into a choice.
Key idea
Use if, elif and else. Python checks the tests in order and runs only the first one that is true. Put narrow tests before broad ones.
Worked example: Order matters
if d < 50:
action = 'slow'
elif d < 15:
action = 'stop'
else:
action = 'go'What happens at d = 10?
- d < 50 is true, so action = 'slow'.
- The elif is never checked. The robot never stops!
Answer: 'slow'. Fix it by testing d < 15 first.
Worked example: Two sensors
A line follower has left and right sensors that read True on the line. Left True, right False: which way should it steer?
- The line is under the left sensor, so the line is to the left.
- Steer left to center it.
Answer: Left.
Why it works
Most robot behavior is a stack of decisions like these, run many times a second. Getting the order right is the difference between a robot that stops at the wall and one that hits it.
Common mistake
Writing an early, broad test that hides a later, narrow one. Test the most specific case first.
Hands-on: a night-light robot
Put a light sensor in a voltage divider on an analog pin. Print the reading every half second while you cover and uncover it. Pick a threshold halfway between dark and bright, and turn an LED on below it. Then add a second threshold for "very dark" and blink.