Python online tutorial

Part 9: Control Flow

Control flow refers to the redirection of execution within a program. We might need to skip some code if a certain condition is met, or repeat some code more than once. We will be covering the 4 main methods of control flow in Python: if-else constructs, for loops, while loops, and functions (in a later page).

If-else

An if-else block is the simplest control flow block possible. Here is the syntax:

if(condition):

# Code snippet 1

else:

# Code snippet 2

# Code snippet 3

If the condition is True, snippet 1 will execute and the program will skip the else block and proceed with snippet 3.

If the condition is False, snippet 2 will execute and the program will continue as normal to snippet 3. Example:

If-elif-else

There is a very important variation of if-else called if-elif-else (if-else if-else). It’s similar to a switch statement in other programming languages – it tests the input against various patterns and executes the code under the matching case and nothing else. In other words, Python will check conditions sequentially top-to-bottom and as soon as it finds a true one it will enter the block and execute it, then skip the rest. This is easier to understand with an example:

Exactly one of the 7 print statements in this example will be executed. A time is taken from the user via the input() in-built function, then it is repeatedly tested until it falls between any of the ranges specified. When this happens, the corresponding message is printed and flow skips to the line immediately following the if-elif-else block. Notice the else section does not contain a condition. This will be the case in every else you write, as they are considered the default or fallback option (in this case, it just relays an error to the user).

Note: for efficiency reasons, when Python finds a true condition it will not bother checking the rest even if they are true too.

Loops

A loop in programming refers to a construct that repeats a body of code a number of times. If this number is known, we must use a for loop – if the number is unknown, we must use a while loop.

For loops

There are four main kinds of for loops in Python. The first 3 are very similar – they all use the built-in range function to generate a list to iterate over. To create them, use the following syntax:

for i in range([start], stop, [step]):

# Loop body

Note if an argument is surrounded by square brackets, it is optional, and it’s compulsory otherwise. Optional arguments are passed in the same format as non-optional ones – without square brackets. As we have at least one compulsory argument, there are three ways to make a for loop combining the three parameters:

  • Using just stop indicates the list should be populated with every number from 0 (inclusive) to stop (exclusive). This is equivalent to all whole numbers in the interval between 0 and stop including 0 and excluding stop, i.e. [0, stop).
  • Using start and stop will generate a list of all whole numbers between start (inclusive) and stop (exclusive).
  • Using all three parameters start, stop and step will populate a list with numbers between start (inclusive) and stop (exclusive), just like above, but will skip every step number. Thus if step is two, it will skip every second number (see example below).
  • It is currently not possible to create a loop with just stop and step, however you can just use 0, stop, step to achieve the same functionality.

Will print numbers 0-9

Will print numbers 1-10

Will print all even numbers 0-20

The fourth type of for loop is special because, instead of generating a range to iterate through, it takes an existing sequence and goes through the elements one by one. This sequence can be any iterable element in Python – the most common type is lists, but you can also loop over dictionaries, files… This kind of for loop also uses the in keyword, and the syntax is very simple. Assuming you have defined a list called myList, to go over it with a for loop you can just use:

for e in myList:

# Loop body

Where e is just a placeholder name for the element (you can call it anything you want).

Note lists in Python can contain multiple types of elements. This loop will print all of them regardless of their type.

While loops

If you recall, we said at the beginning that if we don’t know how many times we want the loop to execute, its more convenient to use a while loop. The basic principle of while loops is that they will execute again and again while a certain condition remains true. As soon as it is false, flow will proceed to the instruction directly after the loop. The test is made directly after the loop body and before the next loop iteration. Here’s how to make one:

while(condition):

# Loop body

Simple, right? The condition can be anything from a quick numerical test such as 5 < 7 to a compound boolean such as x not in list1 and x != 4.

A really simple while loop: Just print out a loop index as long as its smaller than 10.

A more advanced example taking a loop count from the user and running that many times.

Break & Continue

It's usually a good idea to make sure your loop will terminate at some point - this is an important consideration, especially when dealing with complex programs that may fill up your RAM memory quickly.

To achieve this, you have many choices. A typical while loop will test an index, say i, against a number, and increment i every loop iteration until it is equal to said number, then exit. However, what if you have a while(True) loop which will execute forever until a keyboard interrupt (Ctrl + C) or a system error? This is where break and continue come into play.

  • The break statement, placed anywhere inside a loop, including within several if-else blocks or other constructs, will break out of the nearest enclosing loop - that is, do no more iterations and skip straight to the line after the loop.
  • The continue statement, placed anywhere inside a loop, will simply skip the rest of the code in the loop body and resume execution at the top of the loop. Placing continue at the very end of a loop body has no effect.

If it's not too clear, here are some examples to help you out: