Skip to content

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")
  • if is checked first.
  • elif adds extra conditions, and you can have as many as you need.
  • else runs 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

a is less than b
a is 5, b is 7

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:

one
2
three

range() generates a sequence of numbers, which is useful when you want to repeat something a fixed number of times:

# range(0, 4) gives 0, 1, 2, 3
for i in range(0, 4):
    print(i)

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:

def driver(robot):
    while robot.running:
        ...

See Match lifecycle.

break and continue

Both work in for loops and while loops.

  • break exits the loop immediately.
  • continue skips 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?
for i in range(0, 10):
    if i < 7:
        continue
    elif i == 9:
        break
    print(i)

Answer

7
8

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

Functions and scope: how to package code so you can reuse it.