Install Python 3 and create a file named robot.py. This educational example prints a decision and does not control real hardware.

Data and conditions

A variable names a value. An if statement chooses a path through your program. Indentation is part of Python syntax; use four spaces inside each block.

distance_cm = 18

if distance_cm < 20:
    print("STOP")
else:
    print("MOVE")

Turn the logic into a function

A function lets you repeat the same decision for different inputs. This function returns STOP below 20 and MOVE otherwise. The for loop tests three distances.

def decide(distance_cm):
    if distance_cm < 20:
        return "STOP"
    return "MOVE"

for distance in [10, 20, 35]:
    print(distance, decide(distance))

Run and extend

Save the file and run the command below. The decisions are STOP, MOVE, MOVE. Add a condition that returns INVALID for a negative distance, before checking the stopping distance.

python3 robot.py

Check your understanding

What does decide(20) return?

MOVE. The condition is less than 20, not less than or equal to 20.

Python — Control Flow ↗