Step 5
Making decisions
Compare values, and choose what to do with if, elif and else.
True or False
A comparison asks a question and gives back a boolean: True or False.
| Comparison | Means |
|---|---|
a < b, a > b | less than, greater than |
a <= b, a >= b | less than or equal, greater than or equal |
a == b | equal (two =, because one = stores a value) |
a != b | not equal |
Combine them with and (both must be true), or (at least one must be) and not:
angle >= 0 and angle <= 3.14
if, elif, else
if runs its indented block only when its condition is true. elif ("else if") tries another condition when the ones above were false, and else catches everything left over:
def describe(speed):
if speed > 1.0:
return "fast"
elif speed > 0:
return "moving"
else:
return "stopped"
Python checks the conditions from the top and runs only the first block whose condition is true. That's why the elif doesn't need to say speed <= 1.0: it's only reached when speed > 1.0 was false.
return ends the function straight away, so nothing after it runs.
Your task
- Write
choose_action(distance). The gripper isdistancemetres from a ball. Return"grab"when it's closer than 0.05 m,"approach"when it's closer than 0.5 m, and"wait"otherwise. - Write
in_limits(angle, low, high). ReturnTruewhenangleis betweenlowandhigh, ends included, andFalseotherwise.
The grader tries values right on the boundaries, so think about < versus <=.