Introducing Control Flow

Very simply put, to “control flow” in your code is to affect the order in which the code in your program is executed. Up until this point in the course, you have seen (and hopefully written) code that executes linearly; for example:

# simple code without any "control flow"
# i.e. no branches in logic, loops, or
# code encapsulation
x = 6
y = 23
print("x + y = ", x + y)
print("x - y = ", x - y)

But what if you want your code to do something different when x is an even number? What if you want to do an additional computation for every number that falls between x and y? By the end of this module, you should understand how to write programs that can accommodate these, and many other, branches in logic.

Control flow tools will vastly expand your ability to write useful code. They are the quintessential building blocks for modern programming languages, and are effectively the same across Python, C, C++, Java, and many others (barring syntactic differences).

As a sneak peek, let’s write a function that counts how many numbers between m and n are divisible by 3

def cnt_div_by_3(m, n):
    """ Counts how many numbers in the interval [m, n] are divisible by 3. """
    count = 0
    for num in range(m, n + 1):
        if num % 3 == 0:  # x % y  gives the remainder of x / y
            count += 1
    return count

(note: there are much more efficient ways of computing this - can you think of any?)

This code contains several critical “control flow” features:

  • The def cnt_div_by_3(m, n): statement signals the definition of a function: a modular block of code, which can be utilized elsewhere in your code.
  • The line for num in range(m, n + 1): signifies a “for-loop” which instructs the code to iterate over a sequence of numbers, executing a common block of code for each iteration.
  • if num % 3 == 0: and else instruct pieces of codes to be executed conditionally - only if a specified condition is met.

In the following sections, you will be formally introduced to if-elif-else blocks, for-loops & iterables, and functions, all so that you can implement effective “control flow” in your code.