Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

3 Program flow control with Conditional Statements and Loops

Pre/Post-test

This test is for testing your current skills in Python. You can use it in two ways:

  • pre-test: to test your skills beforehand. If you are already proficient in Python, and can do this test within approximately 15 minutes, you can scan through the notebook rather than carefully reading each sentence.

  • post-test: to test your skills after Notebook 3. Check whether you learned enough.

Including password protection
Although the supervisors are impressed by the work Eric is doing, his co-workers are not as happy by the quick progress Eric is making. Due to the large number of error messages in his code recently, he is convinced someone is messing with his code... Therefore he decides to write a program that asks the user to enter the password and checks whether it is correct. As a typo might occur, the user has three tries, after which the program should shut down. After every try, tell the user whether the password is correct or not and how many tries are left. If the user has not provided the right passwork within the required number of attempts, provide a warning message.

Write the code.

Learning objectives

In this notebook, we will learn how to control the flow of execution of Python code using conditional statements and loops.

After completing this notebook, you are able to:

  • create conditional branching statements using if, elif, and else

  • formulate conditions using ==, <, >

  • combine logical conditions using and and or

  • create a while loop that exits on a particular condition

  • create a for loop that loops over a range of numbers using the range() command

  • exit loops using the break command

  • skip the rest of a code block in a loop using continue

Conditional statements

A powerful concept in programming languages are pieces of code that allow you to control if segments or your code are executed or not based of the value of variables in your code.

In this section, we will look at some of the features of the Python language for conditional execution of your code.

The if statement

We have already seen an example of the if statement in the previous notebook. The syntax of the if statement is as follows:

Here, expression is a piece of code that evaluates to either the value True or False. Here are a few simple examples:

Check if 103.51 is true:

Check if -1 is true:

Check if condition statements work with boolean variables:

Check if conditional statements work with numerical variables:

Comparison and test operators

In the above, the expression in the if statements were all directly values that are either True or False (except for the example of not False).

More generally, however, the expression can also include comparisons. Some examples of numerical comparisons are given here below:

In addition to the == operator, there are also several other comparison operators such as <, >, >=, <=, !=

Logical operations

Python also allows you to build the expression out of logical combinations of several conditions using the keywords and, or, and not. The value of these operators is as follows

  • and evaluates to True if both conditions are True

  • or evaluates to True if either condition is True

  • notevaluates to True if condition is not True

Below are a few examples.

To understand what happened in part (b), we have to know if Python first performs the operation False or True or if it performs the operation not False first. The rules for which order Python does things, in can be found in the documentation for operator precedence. In the example above, we can see that the not operator had precedence and Python performed the not before it performed the or.

What if I wanted to have Python perform the or first? You do this by enclosing True or False in brackets:

The elif and else statements

In Python, you can combine the if statement with elif and else commands in a chain in order to allow you to take actions in the case that the starting if statement was false.

elif (else if) is a command that allows you to check another condition if the condition of the starting if is False. Note that if the if criterion is True, the elif statement will be skipped and not checked.

else is a command that allows you to execute some code if all of the if and all the elifs are False.

Note that to be part of the “chain”, all the elifs and the last else must follow directly after each other’s code blocks with no other code in between. And a new if always starts a new chain. You can see how this works in the following examples:

Since the code inside your if code block is just regular code, you can also add another if statement inside that code block. This creates a nested if statement inside your first one:

Loops

Loops are a construction in a programming language that allow you to execute the same piece of code repeatedly.

In Python there are two types of loops: while loops and for loops. We will look at while loops first and then move on to the more common for loops.

The while loop

Using the while command, you can specify that a block of code gets executed over and over again until a certain condition is satified:

As long as expression is True, then the code block will be executed over and over again.

A simple example where we use a while loop to count to 10:

In this example here, we use a while loop to add up all the numbers between 1 and 10:

Note that with while loops, you have to be careful to make sure that your code block does something that results in your expression becomes false at some point, otherwise the loop will run forever.

For example, when initially I wrote the above cell to calculate the sum, I forgot the i = i+1 line of code:

This code will never finish: it will go into an infinite loop! (You can see that it is still running because the * beside the In text never gets turned into a number.) Note that for this will have to manually stop the kernel using the stop button in the toolbar or it will run forever...

When should I use a while loop?

For both of the examples above, one would typically use for loop, which we will see in the next section. One place where while loops are very useful is if you do not know ahead of time how many iterations of the loop you will need.

For example, let’s consider the following sum:

S(n)=∑i=1nsin⁡2(i)S(n) = \sum_{i=1}^n \sin^2(i)

Let’s say we want to know: for which nn does the sum exceed 30? We can easily check this with a while loop:

Note here I have also used a new operator +=: this is a special assignment operator that increments the variable by the specified amount. a += 1 is equivalent to a = a + 1 (it just saves a bit of typing, remember: programmers are lazy...).

The for loops

The for loop is designed to execute a piece of code a fixed number of times. The syntax of the for loop is:

In each subsequent iteration of the for loop, the variable i is assigned next value that is supplied in the list values.

We can repeat our sum calculation above using the following for loop:

It would, however, be much more convenient if we would not have to type all the numbers. Our could be something like this:

And that brings us to the range function...

Enumerate

Sometimes it might be useful to obtain both the element and the index of an array or list. One tool that lets you do that is enumerate. Enumerate works on every iterable (so on numpy arrays, lists, ...)

Example Below we have taken a sentence and have broken these down into a list of single words. We want to return the indeces of the words useful. Note that there are way better ways to do this.

The range() function

You can imagine that if we wanted to perform the sum up of all numbers from 0 to 100, it would be very annoying to type out all of the numbers. For this, Python has a convenient function range(), than can automatically generate ranges of numbers for you!

The range function can be used in a couple of different ways, which we will look at here. We will see, however, that range does some funny things, which is related to the fact that Python “counts from zero” (more on this later).

But let’s look just at some concrete examples for now:

range(N): Print a range of N numbers starting from zero

If you give range only one argument, it will give a range of numbers starting from 0, and a total number of numbers determined by the argument.

As an explicit example, range(10) is equivalent to (0,1,2,3,4,5,6,7,8,9):

range(N,M): Print a range of numbers starting from N and ending at M-1

If you give range two arguments range(N,M), it will give a range of numbers starting from N and stopping at M-1.

You might ask: why not stop at M? If you say the words “range from N to M”, you would think that this range should include M?

There are two reasons I can think of:

  1. For programmers, it is nice that range(0,10) and range(10) do the same thing

  2. It will be handy later that range(j, j+N) will then always give you N numbers in the range

Maybe there are more, I’m not sure (you’d have to ask the nerds who wrote Python...). But in any case, you just need to remember that range(N,M) stops at M-1...

range(N,M,S): Print a range of numbers less than M, starting from N, with steps of S

This is like the last one, but now with the chance to change the steps:

Note that the range function works only with integers: range(1,11,0.5) is not allowed. (For floating point ranges, you can use the numpy function arange, more on that later...)

Using for loops with things other than ranges of numbers

In the examples above, we looked at using for loops to iterate through a list of integers.

In Python, however, for loops are much more flexible than only iterating over numbers: for loops can iterate over any iteratable object, including 1-D numpy arrays, which we will see in later notebooks.

But, as an example, here is a piece of code that uses the numpy random number generator to calculate the sum of 10 random integers between 0 and 100:

Manually exiting or skipping a loop using break and continue

In addition to the examples we saw above, Python offers two extra commands for controlling the flow of execution in a loop: break and continue

break is a command you can use to force the exiting of either a for loop or a while loop. For example, you can replace the while loop above using something like this:

It looks funny at first, because while True looks like you will loop forever! But of course, you are saved by the break statement.

Using break statements can sometimes make your code more readable, particularly if you want to be able to exit the loop under different conditions, or have an exit condition trigger a certain piece of code. Here is an example of two conditions:

The statement continue is used if you want to skip the rest of the code in the code block and restart the next loop. This can sometimes be useful if as a way of avoiding adding an else statement. (Remember, programmers are lazy typers...and it can be useful if you have a big long complicated block of code...)

This is probably not a great example (if you are smart you can do this with less typing), but in any case, you now know what continue does.