Python/Program Flow and Logicals

From ECLR
Revision as of 11:41, 14 October 2013 by Jb (talk | contribs) (Improvements on the above)
Jump to: navigation, search

Preliminaries

One important thing to understand when programming in Python is that correct indenting of code is essential. The Python programming language was designed with readability in mind, and as a result forces you to indent code blocks, e.g.

  • while and for loops
  • if, elif, else constructs
  • functions

The indent for each block must be the same, the Python programming language also requires you to mark the start of a block with a colon. So where MATLAB used end to mark the end of a block of code, in Python a code block ends when the indenting reverts. Other than this, simple Python programmes aren't dissimilar to those in MATLAB.

For example, the simplest case of an if conditional statement in Python would look something like this

if condition:
   statement1
   statement2
   ...

where the code in lines statement1, statement2, ... is executed only if condition is True. Sharp sighted readers might spot another difference to MATLAB, in Python there is no need to add a semicolon at the end of a line to suppress output, since Python produces no output for lines involving assignment (i.e. lines with the = sign).

The boolean condition can be built up using relational and logical operators. Relational operators in Python are similar to those in MATLAB, e.g. == tests for equality, > and >= test for greater than and greater than or equal to respectively. The main difference is that!= tests for inequality in Python (compared to ~= in MATLAB). Relational operators return boolean values of either True or False.

And Python's logical operators are and, or and not, which are hopefully self explanatory.

The if functionality can be expanded using else as follows

if condition:
   statement1
   statement2
   ...
else:
   statement1a
   statement2a
   ...

where statement1, statement2, ... is executed if condition is True, and statement1a, statement2a, ... is executed if condition is False. Note that the code block after else starts with a colon, and this code block is also indented.

Finally, the most general form of this programming construct introduces the elif keyword (in contrast to elseif in MATLAB) to give

if condition1:
   statement1
   statement2
   ...
elif condition2:
   statement1a
   statement2a
   ...
   ...
   ...
elif conditionN:
   statement1b
   statement2b
   ...
else:
   statement1c
   statement2c
   ...

Like MATLAB, Python has while and for loops. Unconditional for loops iterate over a list of values

for LoopVariable in ListOfValues:
   statement1
   statement2
   ...

and repeat for as many times as there are elements in ListOfValues, each time assigning the next element in the list to LoopVariable. The code block associated with the loop is identified by a colon and indenting as described above.

There are various ways of creating a list in Python. The range function can be used to create sequences of integers with a defined start, stop and step value. For example to create a list containing the four values 1, 4, 7 and 10, i.e. a sequence starting at 1 with steps of 3, we can use range(1,11,3). Note that the stop value passed to the range function is not included in the list, i.e. range(1,10,3) would produce only the three numbers 1, 4 & 7. We can verify this at the Python command prompt, i.e.

>>> range(1,11,3)
[1, 4, 7, 10]
>>> range(1,10,3)
[1, 4, 7]

This might seems strange, but makes more sense when we realise the start and step values are optional, and the range function assumes default values of 1 for these if they are not given, i.e. range(N) returns N values starting at 1, e.g.

>>> range(5)
[0, 1, 2, 3, 4]
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Python lists can also be created from a sequence of values separated by commas within square brackets, e.g. MyList = [1.0, "hello", 1] creates a list called MyList containing 3 values, a floating point number 1.0, the string hello and an integer 1. This example demonstrates that Python lists are general purpose containers, and elements don't have to be of the same class. It is for this reason that lists are best avoided for numerical calculations unless they are relatively simple, as there are much more efficient containers for numbers, i.e. NumPy arrays, which will be introduced in due course.

Conditional while loops are identified with the while keyword, so

while condition:
   statement1
   statement2
   ...

will repeatedly execute the code block for as long as condition is True.

As in MATLAB, Python allows us to break out of for or while loops, or continue with the next iteration of a loop, using break and continue respectively.

for

We now look at the Python equivalents of the MATLAB code discussed in the MATLAB page on Program Flow and Logicals. A description of the mathematics is available on the MATLAB page, for brevity it is not repeated here. In the case when the error terms in e are known in advance, the Python version of the algorithm is:

  1. Find length of the list containing the error terms e: T=len(e)
  2. Initialize a list y with the same length as vector e: y=[0.0]*T
  3. Compute y[0]=phi0+phi1*y0+e[0]. Please remember, we assume that [math]y_0=E(y)=\phi_0/(1-\phi_1)[/math]
  4. Compute y[i]=phi0+phi1*y[i-1]+e[i] for [math]i=1[/math]
  5. Repeat line 4 for [math]i=2,...,(T-1)[/math]

A simple implementation in Python follows, and a description of how to run this code is given towards the end of this page.

T=len(e)
y=[0.0]*T
y0=phi0/(1-phi1)
y[0]=phi0+phi1*y0+e[0]
for i in range(1,T):
   y[i]=phi0+phi1*y[i-1]+e[i]

and for comparison the MATLAB code is

  T=size(e,1);
  y=zeros(T,1);
  y0=phi0/(1-phi1);
  y(1)=phi0+phi1*y0+e(1);
  for i=2:T
    y(i)=phi0+phi1*y(i-1)+e(i);
  end

One important difference to MATLAB is that Python list and array indexing starts at 0 and indices are placed inside square brackets (array indices start at 1 in MATLAB). It is also important to understand that Python generally assumes a number to be integer unless there is something to indicate it is a floating point value. Consider the line y=[0.0]*T that preallocates a Python list containing T floating point numbers all set to zero. If this had been written as y=[0]*T the list would contain T integers instead. We can demonstrate this at the Python prompt using the type function, which tells us the class of an object, e.g.

>>>type(0.0)
<type 'float'>
>>> type(0)
<type 'int'>
>>> type(0e0)
<type 'float'>

Controversially, the behaviour of integer division changed in Python version 3, compared to version 2, and it is worth mentioning this now. In Python 2

>>>type(1/2)
<class 'int'>
>>> 1/2
0

whereas in Python 3

>>>type(1/2)
<class 'float'>
>>> 1/2
0.5

As Python 3 is expected to be the future of Python, we recommend using this version unless you have a good reason not to.

if else

As above, a description of the mathematics can be found on the MATLAB page on Program Flow and Logicals. The Python algorithm is now

  1. Find length of the list containing the error terms e: T=len(e)
  2. Initialize a list y with the same length as e: y=[0.0]*T
  3. Check whether abs(phi1)<1. If this statement is true, then y0=phi0/(1-phi1). Else, y0=0. Please remember, we set [math]y_0=E(y_0)[/math].
  4. Compute y[0]=phi0+phi1*y0+e[0].
  5. Compute y[i]=phi0+phi1*y[i-1]+e[i] for [math]i=1[/math]
  6. Repeat line 5 for [math]i=2,...,(T-1)[/math]

This can be implemented in Python as

T=len(e)
y=[0.0]*T
y0=0.0
if abs(phi1)<1:
   y0=phi0/(1-phi1)
y[0]=phi0+phi1*y0+e[0]
for i in range(1,T):
   y[i]=phi0+phi1*y[i-1]+e[i]

which is relatively similar to the MATLAB version

  T=size(e,1);
  y=zeros(T,1);
  y0=0;
  if abs(phi1)<1
  y0=phi0/(1-phi1);
  end
  y(1)=phi0+phi1*y0+e(1)
  for i=2:T
    y(i)=phi0+phi1*y(i-1)+e(i);
  end

while

The Python alternative of the above code using a conditional while loop implements the following algorithm (remember that this contrived example is purely for demonstration purposes, and usually while loops are used when the number of iterations is not known in advance).

  1. Find length of the list containing the error terms e: T=len(e)
  2. Initialize a list y with the same length as e: y=[0.0]*T
  3. Check whether abs(phi1)<1. If this statement is true, then y0=phi0/(1-phi1). Else, y0=0.
  4. Compute y[0]=phi0+phi1*y0+e[0].
  5. Compute y[i]=phi0+phi1*y[i-1]+e[i] for [math]i=1[/math]
  6. Increase i by 1, i.e. [math]i=i+1[/math].
  7. Repeat lines 5-6 whilst [math]i\lt T[/math]

The Python code is a follows.

T=len(e)
y=[0.0]*T
y0=0.0
if abs(phi1)<1:
   y0=phi0/(1-phi1)
y[0]=phi0+phi1*y0+e[0]
i=1
while i < T:
   y[i]=phi0+phi1*y[i-1]+e[i]
   i+=1

This introduces a shorthand also used in other programming languages (e.g. C) as i+=1 is shorthand for i=i+1. This shorthand can be used with other operators, e.g. i*=10 is equivalent to typing i=i*10.

For comparison, the MATLAB code is

  T=size(e,1);
  y=zeros(T,1);
  y0=0;
  if abs(phi1)<1
  y0=phi0/(1-phi1);
  y(1)=phi0+phi1*y0+e(1)
  i=2;
  while i<=T
    y(i)=phi0+phi1*y(i-1)+e(i);
    i=i+1;
  end

Improvements on the above

Like MATLAB, Python allow us to adopt a programming style that both simplifies code, and also allows programs to run faster, in particular:

  1. Operators, functions and logical expressions can work not only on scalars, but also on vectors, matrices and, in general, on n-dimensional arrays
  2. Subvectors/submatrices can be extracted using logical 0-1 arrays

However, this functionality isn't part of core Python, and requires us to use a Python package called [[1]], which adds other useful functionality including pseudo-random number generators. There are many other Python Packages, which are listed at [Python Package Index].

Before using a Python package, the package to must be imported, e.g.

import numpy

Functions within a package are located within namespaces, and namespaces allow package writers to choose functions names without worrying about whether that function name has been used elsewhere. For example, NumPy includes a rand function, which exists within a namespace called random. And the random namespace is within the NumPy namespace (which is called numpy). After importing NumPy we can use the rand function, but have to include the namespace within the function call, e.g. to use at the Python command prompt

>>> import numpy
>>> A = numpy.random.rand(5)
>>> A
array([ 0.50639352,  0.44000756,  0.16118149,  0.69615487,  0.3887179 ])

So numpy.random.rand refers to the rand function in the numpy.random namespace. While this allows safe reuse of names, it does potentially introduce a lot of extra typing, and so Python includes ways to simplify our code. For example, we can import individual functions from a namespace as follows

>>> from numpy.random import rand
>>> A = rand(4)
>>> A
array([ 0.25254338,  0.95567921,  0.28244092,  0.92564069])

and we can also rename the function as we import it

>>> from numpy.random import rand as nprand
>>> A = nprand(4)
>>> A
array([ 0.96127673,  0.57402182,  0.36119553,  0.99832014])

In addition we can rename the namespace

>>> import numpy.random as npr
>>> A = npr.rand(4)
>>> A
array([ 0.4282803 ,  0.80106321,  0.7078212 ,  0.13823879])

Running code in Python