logo

Ziffur

Control Flow Basics: How to Write Computer Programs (using Python)

Control Flow Basics: How to Write Computer Programs (using Python)

6 July 2021

If you've made it this far in the series, great! This is where the real fun begins. If you're new, no worries! In this series on computer science, we make sure not to overwhelm you with too much information at once. Instead, we take only the concepts which we deem essential and try to stack them on top of each other to quickly build up to something meaningful and practical.

So far, we've covered:

  • Binary numbers and their significance in computer science.
  • Booleans, the most basic binary data type, and how to use Boolean algebra and if statements to create dynamic behavior in a computer program.
  • Variables and some fundamental data types: numbers (integer/float), strings, arrays (lists), and dictionaries.
  • How to quickly set up a Python interpreter.

Once we add control flow into the mix, we have everything we need to write some real code. To achieve this, we will introduce two control flow concepts: if/else statements, for loops and while loops.

if/else Statements

We briefly introduced this concept in our article on Boolean algebra to show how booleans play an important role in controlling the behavior of a computer program. For now, let's focus on the syntax we use when writing if/else statements.

Syntax is an important part of a programming language. Since computers are incapable of creative thinking, they require very precise instructions in order to perform the tasks we want them to. This means that simple inaccuracies (such as typos) in source code can cause an entire software system to collapse. In our article about Boolean algebra, for example, we presented the following code snippet:

if isUserLoggedIn and (not isCartEmpty):
    # Navigate to checkout page
else:
    # Stay on the current page

If we save this code in a file and try to run it as-is, we get the following error:

johndoe@johndoe-ThinkPad-T490s:~$ python example.py
  File "example.py", line 3
    else:
    ^
IndentationError: expected an indented block

This happens because we failed to follow the proper syntax for an if statement. An if statement in Python must have:

  • The if keyword.
  • A condition. This can be any expression which the Python interpreter can resolve as a Boolean value. In our case, we use Boolean algebra (the and & not operators) to build this condition from two variables (isUserLoggedIn and isCartEmpty). We assume that these variables have Boolean values because they are named using yes/no questions ("Is User Logged In?" "Yes/True or No/False").
  • A colon (:) followed by a newline character (return). This tells the Python interpreter that the condition is over.
  • A code block to be executed if the condition evaluates to True. This must be indented using any number of spaces or tab characters (consistent with other indentation in the same file). This indentation informs the Python interpreter of the beginning and the end of the code block.

An else statement is optional (immediately following the if statement) and defines a code block for the interpreter to run if the if condition evaluates to False.

Our example fails with an IndentationError despite our comment (# Navigate to checkout page)1^1 being indented 4 spaces. This happens because the Python interpreter does not care about comments in code, they are written for humans only. In order to bypass this error, we can use the pass keyword to explicitly tell the interpreter to do nothing. This counts as an expression and therefore constitutes a valid code block. Let's update the code:

if isUserLoggedIn and (not isCartEmpty):
    # Navigate to checkout page
    pass
else:
    # Stay on the current page
    pass

If we run this code again, we get a new error:

johndoe@johndoe-ThinkPad-T490s:~$ python example.py
Traceback (most recent call last):
  File "example.py", line 1, in <module>
    if isUserLoggedIn and (not isCartEmpty):
NameError: name 'isUserLoggedIn' is not defined

The IndentationError is gone, meaning our if/else statement is valid, but we now get a NameError because the variables isUserLoggedIn and isCartEmpty have not been defined. We can bypass this error by "hard-coding" them with made-up values, like so:

isUserLoggedIn = True
isCartEmpty = True
if isUserLoggedIn and (not isCartEmpty):
    # Navigate to checkout page
    pass
else:
    # Stay on the current page
    pass

If we run this now, we should see no output. That's good! That means the syntax is valid and the Python interpreter understands what to do. We just haven't asked it to show us any output yet.

Before you read further, please take a moment to predict, based on these hard-coded values, whether the program will go through the if block (Navigate to checkout page) or the else block (Stay on the current page). Use the truth tables in our Boolean algebra article to guide you through the process. If you're feeling extra ambitious, write up your own truth table for isUserLoggedIn and (not isCartEmpty) for all four combinations of isUserLoggedIn and isCartEmpty.

When you're ready to verify your answer, you can use the interactive Python console to help you. Forget about the if/else statement for now and instead just set the variables and type in the condition, like so:

$ python
>>> isUserLoggedIn = True
>>> isCartEmpty = True
>>> isUserLoggedIn and (not isCartEmpty)

The code we've written so far in this section doesn't do anything interesting at all. Hopefully though, you now have a good feeling for how to write valid Python syntax and how to proceed if your program fails to run. In the next section we'll focus less on semantics and more on building something meaningful.

for Loops

Loops are a programmer's bread and butter. This is where we can finally tell the computer to do lots of work without having to write lots of code. They come in two main forms: for and while. We will cover each one individually.

A for loop is used to iterate over a finite sequence of values, such as a list:

for name in ['Alice', 'Bob', 'Charlie']:
    print(name)
# Alice
# Bob
# Charlie

Or a range:

for number in range(5)
    print(number)
# 0
# 1
# 2
# 3
# 4

Notice how computers tend to start counting from zero while humans are used to starting from one. This is a very important thing to get used to since forgetting about it can lead to some confusing errors.

Using variables, we can implement aggregate functions for the values in a list. Imagine that we have a shopping cart on an e-commerce website filled with items. If we put all of these prices in a list named prices, we can calculate the total price at checkout like so:

total = 0
prices = [10, 10, 20, 3.50, 5]
for price in prices:
    total = total + price
print(total)
# 48.5

Notice how the variable total is set to 0 at the start and updated on every iteration of the loop.

while Loops

while loops are related to for loops in that they re-run a block of code multiple times. Instead of looping a specific number of times, a while loop checks a condition to determine whether to run the next iteration.

The structure is somewhat similar to an if/else statement. If the condition in the while loop evaluates to True, the next iteration is run before checking the condition again. If the condition evaluates to False, the interpreter stops running the loop and continues with the rest of the program. Here's an example of how to count using while loops:

i = 0
while i < 5:
    print(i)
    i = i + 1
# 0
# 1
# 2
# 3
# 4

Normally we try to give descriptive and obvious names to variables. We make exceptions for very common patterns such as i, which is commonly used to count iterations in a loop.

We need to be a little careful with while loops. If the condition always evaluates to True, the loop will never stop running (unless the operating system forces it to). This can cause programs not only to crash but also to take up a lot of resources from the computer it runs on. For most general programming, for loops are more common and practical. while loops do have their uses, though, especially in interactive programs, such as games, which usually continue running until the user chooses to stop.

In this article we used the functions print() and range(). These functions are built into Python but we can also write our own, allowing us to create general programs whose output depends on the input we provide. The next article will cover this in depth.

Tags

Computer Science
Programming