Dark theme

Control Flow I: Branching and Loops
[outline]


In this part we look at control flow: specifically branching in the code, and looping multiple times through the same code. The latter is especially useful when applying processing to containers.


First up, we'll look at branching: allowing something to decide which of two bits of code to run.

Branching (powerpoint)

Further info:

With regards the inefficiency of if-else-if ladders; other languages have a switch/case statement (java for example), which is less efficient than a single if-else, but more efficient that a ladder. Python doesn't have this: info; info). However, you can build similar if you have a massive number of choices it is fairly advanced. You'll need to know how to write functions, which we'll cover later in the course. Of all the solutions on this stackoverflow page, this seems a nice one:
def f(x): return { 'a': 1, 'b': 2 }.get(x, 9)

In C-family languages, the ternary assignment looks like this:
b = (a < 5) ? "less than 5": "more than five";
which is probably equally confusing.


Quiz: In the following code prints _____________________

a = False
if (not a == True):
    print("First")
else:
    print("Second")

  1. "True".
  2. "First".
  3. "Second".

Correct! This shows some of the complications involved in using boolean values in conditions. As a is not equal to True, the comparison results in False, however not checks whether something is False, so in total, the whole condition is True. Crazy! b+b.


The second major control flow statements are associated with running a single chunk of code multiple times with slight variation. We call these 'loops'.


Loops (powerpoint)

Further info:

In general then, it is best to use while when there is some condition to reach; the for in construction when looping through collections; and for i in range only when you need to loop through multiple arrays, for example to compare or operate on the positions across different arrays.

 


Quiz: In the following code, i is generated by ________________________________________

for i in range (1,10,2):
    print(i)

  1. setting i to 1 and adding 1 to it each iteration.
  2. setting i to 1 and adding 2 to it each iteration.
  3. generating objects representing the numbers 1,3,5,7,9 and processing each in sequence.

Correct! Although it looks like i is an incrementing counter, it isn't. Even if you deal with numbers there is no relation between subsequent numbers once the iterations start: they are generated as a sequence of objects at the start and then any notion of them being related disappears.


Finally, let's see how to use loops to process 2D datasets. Such algorithms are key to many data processing needs: from processing files of data to image processing.


2D Loops (powerpoint)

Further info:

Here's an example of using the different number of times actions happen in nested loops to achieve something. It prints a 2D container such that each value on a line is space separated, with such that the print drops a line at the end of each line. This is in contrast with print(data) which would print it comma and space separated.

for i in range(len(data)):
    for j in range(len(data[i])):
        print(data[i][j] end = " ")         # Print with space not newline
    print("") # Standard print, dropping a line.

There are a wide variety of options for sorting containers, including defining the kind of sorting you want; see the documentation on sorting for info.