Learn Programming with Python — Controlling Execution Flow

Posted on April 30, 2020 in Learn Python

Learn Programming with Python — Controlling Execution Flow

In this instalment we’ll explore how to control which parts of your program are executed.

Photo by @divinetechnygirl https://www.pexels.com/@divinetechygirl

Learn Programming with Python — Controlling Execution Flow

In this instalment we’ll explore how to control which parts of your program are executed.

What is “Execution Control Flow”

At its simplest, every programmer, practically every day, will need to control if and when a particular statement should execute. Falling back on the ATM example introduced in the previous instalment in this series, “Learn Programming with Python — Introduction to Functions”, we know that the ATM should only issue cash if a series of test conditions are met. At the heart of execution control flow is the programmer’s intent to only execute certain functions of the program when they are needed, and otherwise not.

If … Elif … Else

Python is easy to read even for novices and non-programmers. This Python code is quite readable:

Except perhaps for line 2. Line 1 retrieves text input — called a string, from the terminal prompt. In line 2 we use the built-in int() function to try to convert the argument to an integer. We need the age in years as an integer (a whole number) because later, in line 4, we perform the less than (<)integer comparison.

The if … else construct is found in most programming languages. Python adds a further twist and allows the elif statement to be used — else if, or otherwise. This next example shows an imaginary situation in which the age of the customer seeking to hire a rental vehicle is processed by a computer program:

In this example we’ve covered all possible ages, and so there is no need for a final else statement. That is not always needed, elif is also not always needed.

The if and elif keywords are always followed by a test condition. The test condition on line 4 is age < 21 — it tests to see if the condition is either True or False. And the colon character, : is used to close the condition statement.

Now we really should talk about Boolean operations.

Boolean Logic

Feel free to read up about George Boole, who left the world a richer place with his Boolean Logic. Today’s computers almost all work on the principles developed by George. True or False. 1 or 0. On or Off. This is the smallest unit of information — literally called a bit in computer science. If you want to read about quantum computers, and how these use the quantum bit, or qubit, head over here, or come back to this later.

George Boole, a Victorian Englishman

George’s contribution was not so much that he wrote about how 0 and 1 existed, but about how they can be combined with each other. He gave us the following logical operations: AND, NOT, OR each resulting in either True or False, 1 or 0.

Anecdote time: poor old George once caught a bad pneumonia during some cold and rainy weather. Unfortunately, medicine being what it was at the time, the treatment was for him to get more of what made him ill in the first place! George was wrapped up in cold, wet blankets until he finally passed away a few days later. So much for how logic can be misapplied!

AND returns True only if both input arguments are equivalent to True. 1 and 0 = False but 1 and 1 = True.

NOT returns True if the input is equivalent to False, and returns False if the input is equivalent to True. It returns the negation. not 0 = True as well as not 1 = False .

OR returns True if either of two arguments are equivalent to true. 1 or 0 = True but 0 or 0 = False.

In Python, these boolean operators are built-in to the language. Here is some code to verify what I wrote above. This code introduces the Boolean operators, and reuses F-Strings and the print() function introduced earlier. I decided to convert the output to either True or False by using the bool() conversion function — similar to how I used int() to force a string into becoming an integer at the top of this article.

Boolean truth table in Python

So why was this excursion into the depths of Boolean logic necessary? It comes back to controlling the program’s execution flow with the If … Elif … Else constructs. We are continually testing conditions to see if they evaluate to true or to false, and based on that outcome to choose which code to execute. The outcome of these evaluations is always either True or False. This leads us directly back to George Boole and his Boolean Logic!

Repeating Parts of a Program

Often times, controlling the execution flow of a computer program will make us want to repeat an operation multiple times. Usually it is a little more complicated, and we want to repeat the same operation on all the members of a set. Let’s say we have a list of all the students in a class, and we want to print a personalised letter to each. This is a really common example of how one function (the function which prints a letter) would be called many times, once for each unique recipient of the letter.

Sets are a special construct in mathematics, take a look here for an introduction. Georg Cantor is credited as having first described them.

Georg Cantor, a Prussian Gentleman

A “Set” is a Collection of Unique, Related Elements

A set is an unordered collection of objects which share something in common. Each element of the set can only occur once. For example, the students in a class form a set, each student is an element of the set. The order of the elements in the set is usually unimportant. In Python we can create a set of the email addresses of the students in a class using curly brackets, like this:

students = {"Emily@gmail.com", "Harish@gmail.com", "Naomi@gmail.com", "Haru@gmail.com"}

If we try to add a name twice, we won’t get an error, but it won’t work either. Sets silently prevent any duplicates:

Creating a set in Python

Repeating a Function on all Elements in a Set with a For Loop

Finally, we’re getting back to the point! We wanted to write a program which uses control flow execution to repeatedly perform the same function on a bunch of different things. Let’s use a for loop construct to print() each element in the set, for now:

Code to loop over each element in a set

Line 3 is where the for loop magic is happening.

  • We use the for each element in a collection construct by starting with for
  • Kind of backward, we first give a name to each element as we pass it. In this case, student
  • Then we specify which collection we want to loop across every element, in our case it is the set called students created in line 1
  • In line 4 we perform a single operation on each element of the set as we pass it by in the loop. We’re keeping it simple and just printing the email address to to the terminal for now.

And this is what we get when we execute the program:

Using the For loop in Python on a Set

Combining For Loops with If Conditions

Let’s say, that for some reason, if the student is called “Emily” then we want do something different. We can accomplish this by using the for loop to inspect every element of the set, and also test each element to see if it is Emily with an If conditional.

Combining For loops with If conditionals in Python

What Have we Achieved?

We’ve covered a lot of ground in this instalment! Primarily we discussed how to control execution flow with If statements to control branches, and For loops to perform repetitions. But also more:

  • If statements to perform code branches based on logical conditions
  • Converting strings to integers
  • The basics of Boolean logic
  • Converting values to True or False Boolean values
  • For loops to perform repetitions on each element in a collection
  • The principles of set theory, an unordered collection of unique elements
  • How to create and loop across sets in Python

In the next instalment I think we should cover more data types. We’ve seen integers, strings, booleans, tuples and sets without really discussing what underlies them, so we’ll cover that ground next!

Articles in this series so far: