Control Flow

Basics

For a given file with a python program, the python interpreter will start at the top and then process the file. We demonstrate this with a simple program, for example:

In [1]:
def f(x):
    """function that computes and returns x*x"""
    return x * x

print("Main program starts here")
print("4 * 4 = %s" % f(4))
print("In last line of program -- bye")
Main program starts here
4 * 4 = 16
In last line of program -- bye

The basic rule is that commands in a file (or function or any sequence of commands) is processed from top to bottom. If several commands are given in the same line (separated by `;`), then these are processed from left to right (although it is discouraged to have multiple statements per line to maintain good readability of the code.)

In this example, the interpreter starts at the top (line 1). It finds the `def` keyword and remembers for the future that the function `f` is defined here. (It will not yet execute the function body, i.e. line 3 – this only happens when we call the function.) The interpreter can see from the indentation where the body of the function stops: the indentation in line 5 is different from that of the first line in the function body (line2), and thus the function body has ended, and execution should carry on with that line. (Empty lines do not matter for this analysis.)

In line 5 the interpreter will print the output Main program starts here. Then line 6 is executed. This contains the expression `f(4)` which will call the function `f(x)` which is defined in line 1 where `x` will take the value `4`. [Actually `x` is a reference to the object `4`.] The function `f` is then executed and computes and returns `4*4` in line 3. This value `16` is used in line 6 to replace `f(4)` and then the string representation `%s` of the object 16 is printed as part of the print command in line 6.

The interpreter then moves on to line 7 before the program ends.

We will now learn about different possibilities to direct this control flow further.

Conditionals

The python values `True` and `False` are special inbuilt objects:

In [2]:
a = True
print(a)
True
In [3]:
type(a)
Out[3]:
bool
In [4]:
b = False
print(b)
False
In [5]:
type(b)
Out[5]:
bool

We can operate with these two logical values using boolean logic, for example the logical and operation (`and`):

In [6]:
True and True          #logical and operation
Out[6]:
True
In [7]:
True and False
Out[7]:
False
In [8]:
False and True
Out[8]:
False
In [9]:
True and True
Out[9]:
True
In [10]:
c = a and b
print(c)
False

There is also logical or (`or`) and the negation (`not`):

In [11]:
True or False
Out[11]:
True
In [12]:
not True
Out[12]:
False
In [13]:
not False
Out[13]:
True
In [14]:
True and not False
Out[14]:
True

In computer code, we often need to evaluate some expression that is either true or false (sometimes called a “predicate”). For example:

In [15]:
x = 30          # assign 30 to x
x > 15          # is x greater than 15
Out[15]:
True
In [16]:
x > 42
Out[16]:
False
In [17]:
x == 30         # is x the same as 30?
Out[17]:
True
In [18]:
x == 42
Out[18]:
False
In [19]:
not x == 42     # is x not the same as 42?
Out[19]:
True
In [20]:
x != 42         # is x not the same as 42?
Out[20]:
True
In [21]:
x > 30          # is x greater than 30?
Out[21]:
False
In [22]:
x >= 30  # is x greater than or equal to 30?
Out[22]:
True

If-then-else

Further information

The `if` statement allows conditional execution of code, for example:

In [23]:
a = 34
if a > 0:
    print("a is positive")
a is positive

The if-statement can also have an `else` branch which is executed if the condition is wrong:

In [24]:
a = 34
if a > 0:
    print("a is positive")
else:
    print("a is non-positive (i.e. negative or zero)")
a is positive

Finally, there is the `elif` (read as “else if”) keyword that allows checking for several (exclusive) possibilities:

In [25]:
a = 17
if a == 0:
    print("a is zero")
elif a < 0:
    print("a is negative")
else:
    print("a is positive")
a is positive

For loop

Further information

The `for`-loop allows to iterate over a sequence (this could be a string or a list, for example). Here is an example:

In [26]:
for animal in ['dog','cat','mouse']:
    print(animal, animal.upper())
dog DOG
cat CAT
mouse MOUSE

Together with the range() command (in chapter 3), one can iterate over increasing integers:

In [27]:
for i in range(5,10):
    print(i)
5
6
7
8
9

While loop

The `while` keyword allows to repeat an operation while a condition is true. Suppose we’d like to know for how many years we have to keep 100 pounds on a savings account to reach 200 pounds simply due to annual payment of interest at a rate of 5%. Here is a program to compute that this will take 15 years:

In [28]:
mymoney = 100         # in GBP
rate = 1.05           # 5% interest
years = 0
while mymoney < 200:  # repeat until 20 pounds reached
    mymoney = mymoney * rate
    years = years + 1
print('We need', years, 'years to reach', mymoney, 'pounds.')
We need 15 years to reach 207.89281794113688 pounds.

Relational operators (comparisons) in `if` and `while` statements

The general form of `if` statements and `while` loops is the same: following the keyword `if` or `while`, there is a condition followed by a colon. In the next line, a new (and thus indented!) block of commands starts that is executed if the condition is True).

For example, the condition could be equality of two variables `a1` and `a2` which is expressed as `a1==a2`:

In [29]:
a1 = 42
a2 = 42
if a1 == a2:
    print("a1 and a2 are the same")
a1 and a2 are the same

Another example is to test whether `a1` and `a2` are not the same. For this, we have two possibilities. Option number 1 uses the inequality operator `!=`:

In [30]:
if a1 != a2:
    print("a1 and a2 are different")

Option two uses the keyword `not` in front of the condition:

In [31]:
if not a1 == a2:
    print("a1 and a2 are different")

Comparisons for “greater” (`>`), “smaller” (`<`) and “greater equal” (`>=`) and “smaller equal” (`<=`) are straightforward.

Finally, we can use the logical operators “`and`” and “`or`” to combine conditions:

In [32]:
if a > 10 and b > 20:
    print("A is greater than 10 and b is greater than 20")
if a > 10 or b < -5:
    print("Either a is greater than 10, or "
          "b is smaller than -5, or both.")
Either a is greater than 10, or b is smaller than -5, or both.

Use the Python prompt to experiment with these comparisons and logical expressions. For example:

In [33]:
T = -12.5
if T < -20:
    print("very cold")

if T < -10:
    print("quite cold")
quite cold
In [34]:
T < -20
Out[34]:
False
In [35]:
T < -10
Out[35]:
True

Exceptions

Even if a statement or expression is syntactically correct, it may cause an error when an attempt is made to execute it. Errors detected during execution are called exceptions and are not necessarily fatal: exceptions can be caught and dealt with within the program. Most exceptions are not handled by programs, however, and result in error messages as shown here

In [36]:
10 * (1/0)
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-36-9ce172bd90a7> in <module>()
----> 1 10 * (1/0)

ZeroDivisionError: division by zero
In [37]:
4 + spam*3
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-37-6b1dfe582d2e> in <module>()
----> 1 4 + spam*3

NameError: name 'spam' is not defined
In [38]:
'2' + 2
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-38-4c6dd5170204> in <module>()
----> 1 '2' + 2

TypeError: Can't convert 'int' object to str implicitly

Schematic exception catching with all options

In [39]:
try:
   # code body
except ArithmeticError:
   # what to do if arithmetic error
except IndexError, the_exception:
   # the_exception refers to the exeption in this block
except:
   # what to do for ANY other exception
else:  # optional
   # what to do if no exception raised

try:
   # code body
finally:
   # what to do ALWAYS
  File "<ipython-input-39-5833dfdab285>", line 3
    except ArithmeticError:
         ^
IndentationError: expected an indented block

Starting with Python 2.5, you can use the with statement to simplify the writing of code for some predefined functions, in particular the `open` function to open files: see http://docs.python.org/tutorial/errors.html#predefined-clean-up-actions.

Example: We try to open a file that does not exist, and Python will raise an exception of type `IOError` which stands for Input Output Error:

In [40]:
f = open("filenamethatdoesnotexist", "r")
---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
<ipython-input-40-11dd75e3491b> in <module>()
----> 1 f = open("filenamethatdoesnotexist", "r")

FileNotFoundError: [Errno 2] No such file or directory: 'filenamethatdoesnotexist'

If we were writing an application with a userinterface where the user has to type or select a filename, we would not want to application to stop if the file does not exist. Instead, we need to catch this exception and act accordingly (for example by informing the user that a file with this filename does not exist and ask whether they want to try another file name). Here is the skeleton for catching this exception:

In [41]:
try:
    f = open("filenamethatdoesnotexist","r")
except IOError:
    print("Could not open that file")
Could not open that file

There is a lot more to be said about exceptions and their use in larger programs. Start reading Python Tutorial Chapter 8: Errors and Exceptions if you are interested.

Raising Exceptions

Raising exception is also referred to as ’throwing an exception’.

Possibilities of raising an Exception

  • raise OverflowError

  • raise OverflowError, Bath is full (Old style, now discouraged)

  • raise OverflowError(Bath is full)

  • e = OverflowError(Bath is full); raise e

Exception hierarchy

The standard exceptions are organized in an inheritance hierarchy e.g. OverflowError is a subclass of ArithmeticError (not BathroomError); this can be seen when looking at `help(’exceptions’)` for example.

You can derive your own exceptions from any of the standard ones. It is good style to have each module define its own base exception.

Creating our own exceptions

LBYL vs EAFP

  • LBYL (Look Before You Leap) vs

  • EAFP (Easer to ask forgiveness than permission)

In [42]:
numerator = 7
denominator = 0

Example for LBYL:

In [43]:
if denominator == 0:
    print("Oops")
else:
    print(numerator/denominator)
Oops

Easier to Ask for Forgiveness than Permission:

In [44]:
try:
    print(numerator/denominator)
except ZeroDivisionError:
    print("Oops")
Oops

The Python documentation says about EAFP:

Easier to ask for forgiveness than permission. This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many try and except statements. The technique contrasts with the LBYL style common to many other languages such as C.

Source: http://docs.python.org/glossary.html#term-eafp

The Python documentation says about LBYL:

Look before you leap. This coding style explicitly tests for pre-conditions before making calls or lookups. This style contrasts with the EAFP approach and is characterized by the presence of many if statements.

In a multi-threaded environment, the LBYL approach can risk introducing a race condition between “the looking” and “the leaping”. For example, the code, if key in mapping: return mapping[key] can fail if another thread removes key from mapping after the test, but before the lookup. This issue can be solved with locks or by using the EAFP approach.

Source: http://docs.python.org/glossary.html#term-lbyl

EAFP is the Pythonic way.