Control Flow#

These notes follow the official python tutorial pretty closely: http://docs.python.org/3/tutorial/

To write a program, we need the ability to iterate and take action based on the values of a variable. This includes if-tests and loops.

Python uses whitespace to denote a block of code.

While loop#

A simple while loop—notice the indentation to denote the block that is part of the loop.

Here we also use the compact += operator: n += 1 is the same as n = n + 1

n = 0
while n < 10:
    print(n)
    n += 1
0
1
2
3
4
5
6
7
8
9

This was a very simple example. But often we’ll use the range() function in this situation. Note that range() can take a stride.

for n in range(2, 10, 2):
    print(n)
2
4
6
8

if statements#

if allows for branching. python does not have a select/case statement like some other languages, but if, elif, and else can reproduce any branching functionality you might need.

x = 0

if x < 0:
    print("negative")
elif x == 0:
    print("zero")
else:
    print("positive")
zero

Iterating over elements#

it’s easy to loop over items in a list or any iterable object. The in operator is the key here.

alist = [1, 2.0, "three", 4]
for a in alist:
    print(a)
1
2.0
three
4
for c in "this is a string":
    print(c)
t
h
i
s
 
i
s
 
a
 
s
t
r
i
n
g

We can combine loops and if-tests to do more complex logic, like break out of the loop when you find what you’re looking for

n = 0
for a in alist:
    if a == "three":
        break
    else:
        n += 1

print(n)
2

(for that example, however, there is a simpler way)

alist.index("three")
2

for dictionaries, you can also loop over the elements

my_dict = {"key1":1, "key2":2, "key3":3}

for k, v in my_dict.items():
    print(f"key = {k}, value = {v}")
key = key1, value = 1
key = key2, value = 2
key = key3, value = 3
for k in sorted(my_dict):
    print(k, my_dict[k])
key1 1
key2 2
key3 3

sometimes we want to loop over a list element and know its index – enumerate() helps here:

for n, a in enumerate(alist):
    print(n, a)
0 1
1 2.0
2 three
3 4

Quick Exercise

zip() allows us to loop over two iterables at the same time. Consider the following two lists:


 a = [1, 2, 3, 4, 5, 6, 7, 8]
 b = ["a", "b", "c", "d", "e", "f", "g", "h"]
 

zip(a, b) will act like a list with each element a tuple with one item from a and the corresponding element from b.

Try looping over these lists together (using zip()) and print the corresponding elements from each list together on a single line.

Quick Exercise

The .split() function on a string can split it into words (separating on spaces).

Using .split(), loop over the words in the string

a = "The quick brown fox jumped over the lazy dog"

and print one word per line