Control flow¶
Control flow decides which lines of code run, and how many times.
Indentation is part of the language
Python uses indentation to decide which lines belong inside an if, a
loop, a function, or a class. Four spaces is the standard. If the
indentation is wrong, the meaning of your program changes.
if, elif, else¶
An if statement runs a block of code only when a Boolean condition is true.
a = 5
b = 7
if a > b:
print("a is more than b")
elif a == b:
print("a is equal to b")
else:
print("a is less than b")
ifis checked first.elifadds extra conditions, and you can have as many as you need.elseruns when nothing above it matched.
Conditions are checked from top to bottom. As soon as one is true, the rest are skipped.
Concept check: what does this print?
a = 5
b = 7
if a > b:
print("a is more than b")
elif a < b:
print("a is less than b")
print("a is 5, b is 7")
Answer
The last print() is not indented, so it is outside the if statement.
It always runs.
for loops¶
A for loop repeats code once for each item in a sequence, such as a list.
list2 = ["one", 2, "three"]
# Access elements in the list one by one
for element in list2:
print(element)
That prints:
range() generates a sequence of numbers, which is useful when you want to
repeat something a fixed number of times:
The end of a range is exclusive
range(1, 10) produces 1 to 9. The last number is not included.
while loops¶
A while loop repeats code for as long as a Boolean condition stays true.
number = 1
while number < 3: # Boolean condition
number += 1 # block of code to loop
print(number) # 3
When the condition becomes false, the loop exits.
If the condition is never false, the loop runs forever. That is sometimes what you want, and sometimes a bug.
MARLIN gives you the condition
In robot code you loop on robot.running, which MARLIN sets to false
when the match phase ends:
See Match lifecycle.
break and continue¶
Both work in for loops and while loops.
breakexits the loop immediately.continueskips the rest of the current pass and starts the next one.
for i in range(1, 10):
print(i)
if i == 5:
break # stops here, does not print 6 to 9
for i in range(1, 8):
if i % 2 == 0:
continue # skips printing even numbers
print(i)
Any code after continue in the same pass does not run.
Concept check: what does this print?
Answer
Values 0 to 6 hit continue, so print() is skipped. 7 and 8 reach
print(). At 9 the loop breaks before printing.
Full documentation: https://docs.python.org/3/tutorial/controlflow.html
What to read next¶
Functions and scope: how to package code so you can reuse it.