Control Flow

We now know how to set variables of various types:

In [1]:
a = 1
b = 3.14
c = 'hello'
d = [a, b, c]

but this doesn't get us very far. One essential part of programming is control flow which is the ability to control how the program will proceed based on for example some conditions, or making parts of the program run multiple times.

if statements

The simplest form of control flow is the if statement, which executes a block of code only if a certain condition is true (and optionally executes code if it is not true. The basic syntax for an if-statement is the following:

if condition:
    # do something
elif condition:
    # do something else
else:
    # do yet something else

Notice that there is no statement to end the if statement, and the presence of a colon (:) after each control flow statement. Python relies on indentation and colons to determine whether it is in a specific block of code.

For example, in the following code:

In [2]:
a = 1

if a == 1:
    print("a is 1, changing to 2")
    a = 2

print("finished")
print(a)
a is 1, changing to 2
finished
2

The first print statement, and the a = 2 statement only get executed if a is 1. On the other hand, print "finished" gets executed regardless, once Python exits the if statement.

Indentation is very important in Python, and the convention is to use four spaces (not tabs) for each level of indent.

Back to the if-statements, the conditions in the statements can be anything that returns a boolean value. For example, a == 1, b != 4, and c <= 5 are valid conditions because they return either True or False depending on whether the statements are true or not.

Standard comparisons can be used (== for equal, != for not equal, <= for less or equal, >= for greater or equal, < for less than, and > for greater than), as well as logical operators (and, or, not). Parentheses can be used to isolate different parts of conditions, to make clear in what order the comparisons should be executed, for example:

if (a == 1 and b <= 3) or c > 3:
    # do something

More generally, any function or expression that ultimately returns True or False can be used.

In particular, you can use booleans themselves:

In [3]:
a = 7
cond = a==1 or a>7
if cond:
    print ("hit")
else:
    print ("miss")
miss

for loops

Another common structure that is important for controling the flow of execution are loops. Loops can be used to execute a block of code multiple times. The most common type of loop is the for loop. In its most basic form, it is straightforward:

for value in iterable:
    # do things

The iterable can be any Python object that can be iterated over. This includes lists or strings.

In [4]:
for x in [3, 1.2, 'a']:
    print(x)
3
1.2
a
In [5]:
for letter in 'hello':
    print(letter)
h
e
l
l
o

A common type of for loop is one where the value should go between two integers with a specific set size. To do this, we can use the range function. If given a single value, it will allow you to iterate from 0 to the value minus 1:

In [6]:
range(10)
Out[6]:
range(0, 10)
In [7]:
for i in range(5):
    print(i)
0
1
2
3
4
In [8]:
for i in range(3, 12):
    print(i)
3
4
5
6
7
8
9
10
11
In [9]:
for i in range(2, 20, 2):  # the third entry specifies the "step size"
    print(i)
2
4
6
8
10
12
14
16
18

If you try iterating over a dictionary, it will iterate over the keys (not the values), in no specific order:

In [10]:
d = {'a':1, 'b':2, 'c':3}
for key in d:
    print(key)
a
b
c

But you can easily get the value with:

In [19]:
for key in d:
    print(key, d[key])
a 1
b 2
c 3
Out[19]:
dict_values([1, 2, 3])

Building programs

These different control flow structures can be combined to form programs. For example, the following program will print out a different message depending on whether the current number in the loop is less, equal to, or greater than 10:

In [20]:
for value in [2, 55, 4, 5, 12, 8, 9, 22]:
    if value > 10:
        print("Value is greater than 10 (" + str(value) + ")")
    elif value == 10:
        print("Value is exactly 10")
    else:
        print("Value is less than 10 (" + str(value) + ")")
Value is less than 10 (2)
Value is greater than 10 (55)
Value is less than 10 (4)
Value is less than 10 (5)
Value is greater than 10 (12)
Value is less than 10 (8)
Value is less than 10 (9)
Value is greater than 10 (22)

Exercise 1

Write a program that will print out all the prime numbers (numbers divisible only by one and themselves) below 1000.

Hint: the % operator can be used to find the remainder of the division of an integer by another:

In [21]:
20 % 3
Out[21]:
2
In [25]:
# enter your solution here
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97
101
103
107
109
113
127
131
137
139
149
151
157
163
167
173
179
181
191
193
197
199
211
223
227
229
233
239
241
251
257
263
269
271
277
281
283
293
307
311
313
317
331
337
347
349
353
359
367
373
379
383
389
397
401
409
419
421
431
433
439
443
449
457
461
463
467
479
487
491
499
503
509
521
523
541
547
557
563
569
571
577
587
593
599
601
607
613
617
619
631
641
643
647
653
659
661
673
677
683
691
701
709
719
727
733
739
743
751
757
761
769
773
787
797
809
811
821
823
827
829
839
853
857
859
863
877
881
883
887
907
911
919
929
937
941
947
953
967
971
977
983
991
997

Exiting or continuing a loop

There are two useful statements that can be called in a loop - break and continue. When called, break will exit the loop it is currently in:

In [23]:
for i in range(10):
    print(i)
    if i == 3:
        break
0
1
2
3

The other is continue, which will ignore the rest of the loop and go straight to the next iteration:

In [24]:
for i in range(10):
    if i == 2 or i == 8:
        continue
    print(i)
0
1
3
4
5
6
7
9

Exercise 2

When checking if a value is prime, as soon as you have found that the value is divisble by a single value, the value is therefore not prime and there is no need to continue checking whether it is divisible by other values. Copy your solution from above and modify it to break out of the loop once this is the case.

In [ ]:
# enter your solution here

while loops

Similarly to other programming languages, Python also provides a while loop which is similar to a for loop, but where the number of iterations is defined by a condition rather than an iterator:

while condition:
    # do something

For example, in the following example:

In [26]:
a = 1
while a < 10:
    print(a)
    a = a * 1.5
print("Once the while loop has completed, a has the value", a)
1
1.5
2.25
3.375
5.0625
7.59375
Once the while loop has completed, a has the value 11.390625

the loop is executed until a is equal to or exceeds 10.

Exercise 3

Write a program (using a while loop) that will find the Fibonacci sequence up to (and excluding) 100000. The two first numbers are 0 and 1, and every subsequent number is the sum of the two previous ones, so the sequence starts [0, 1, 1, 2, 3, 5, ...].

Optional: Store the sequence inside a Python list, and only print out the whole list to the screen once all the numbers are available. Then, check whether any of the numbers in the sequence are a square (e.g. 0*0, 1*1, 2*2, 3*3, 4*4) and print out those that are.

In [27]:
# enter your solution here
a, b = 0, 1
while a < 100000:
    print (a)
    a, b = b, a + b
0
1
1
2
3
5
8
13
21
34
55
89
144
233
377
610
987
1597
2584
4181
6765
10946
17711
28657
46368
75025
In [29]:
l = [0]
i = 0
x = 1

while x < 100000:
    l.append(x)
    x = l[i] + l[i+1]
    i = i + 1

print (l)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025]
In [ ]: