Difference between revisions of "Python/Program Flow and Logicals"
Line 1: | Line 1: | ||
= Preliminaries = | = Preliminaries = | ||
− | One | + | 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 | * while and for loops | ||
* if, elif, else constructs | * if, elif, else constructs | ||
Line 13: | Line 13: | ||
... | ... | ||
</source> | </source> | ||
− | where the code in lines <source lang="python" enclose=none>statement1</source>, <source lang="python" enclose=none>statement2</source>, <source lang="python" enclose=none>...</source> is executed only if <source lang="python" enclose=none>condition</source> is | + | where the code in lines <source lang="python" enclose=none>statement1</source>, <source lang="python" enclose=none>statement2</source>, <source lang="python" enclose=none>...</source> is executed only if <source lang="python" enclose=none>condition</source> is <source lang="python" enclose=none>True</source>. 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. |
− | The <source lang="python" enclose=none>condition</source> can be built up using relational and logical operators. Relational operators in Python are similar to those in MATLAB, e.g. <source lang="python" enclose=none>==</source> tests for equality, <source lang="python" enclose=none>></source> and <source lang="python" enclose=none>>=</source> test for '''greater than''' and '''greater than or equal to''' respectively. The main difference is that<source lang="python" enclose=none>!=</source> tests for inequality in Python, compared to <source | + | The boolean <source lang="python" enclose=none>condition</source> can be built up using relational and logical operators. Relational operators in Python are similar to those in MATLAB, e.g. <source lang="python" enclose=none>==</source> tests for '''equality''', <source lang="python" enclose=none>></source> and <source lang="python" enclose=none>>=</source> test for '''greater than''' and '''greater than or equal to''' respectively. The main difference is that<source lang="python" enclose=none>!=</source> tests for '''inequality''' in Python, compared to <source enclose=none>~=</source> in MATLAB. Relational operators return boolean values of either <source lang="python" enclose=none>True</source> or <source lang="python" enclose=none>False</source>. |
And Python's logical operators are <source lang="python" enclose=none>and</source>, <source lang="python" enclose=none>or</source> and <source lang="python" enclose=none>not</source>, which are hopefully self explanatory. | And Python's logical operators are <source lang="python" enclose=none>and</source>, <source lang="python" enclose=none>or</source> and <source lang="python" enclose=none>not</source>, which are hopefully self explanatory. | ||
Line 29: | Line 29: | ||
... | ... | ||
</source> | </source> | ||
− | where <source lang="python" enclose=none>statement1</source>, <source lang="python" enclose=none>statement2</source>, <source lang="python" enclose=none>...</source> is executed if <source lang="python" enclose=none>condition</source> is | + | where <source lang="python" enclose=none>statement1</source>, <source lang="python" enclose=none>statement2</source>, <source lang="python" enclose=none>...</source> is executed if <source lang="python" enclose=none>condition</source> is <source lang="python" enclose=none>True</source>, and <source lang="python" enclose=none>statement1a</source>, <source lang="python" enclose=none>statement2a</source>, <source lang="python" enclose=none>...</source> is executed if <source lang="python" enclose=none>condition</source> is <source lang="python" enclose=none>False</source>. Note that the code block after the <source lang="python" enclose=none>else</source> starts with a colon, and this code block is also indented. |
Finally, the most general form of this programming construct introduces the <source lang="python" enclose=none>elif</source> keyword (in contrast to <source enclose=none>elseif</source> in MATLAB) to give | Finally, the most general form of this programming construct introduces the <source lang="python" enclose=none>elif</source> keyword (in contrast to <source enclose=none>elseif</source> in MATLAB) to give | ||
Line 53: | Line 53: | ||
</source> | </source> | ||
− | Like MATLAB, Python has while and for loops. Unconditional for loops iterate over a list of values | + | Like MATLAB, Python has while and for loops. Unconditional for loops iterate over a '''list''' of values |
<source lang="python">for CounterVariable in ListOfValues: | <source lang="python">for CounterVariable in ListOfValues: | ||
Line 62: | Line 62: | ||
and repeat for as many times as there are elements in the <source lang="python" enclose=none>ListOfValues</source>, each time assigning the next element in the list to the <source lang="python" enclose=none>CounterVariable</source>. The code block associated with the loop is identified by a colon and indenting as described above. | and repeat for as many times as there are elements in the <source lang="python" enclose=none>ListOfValues</source>, each time assigning the next element in the list to the <source lang="python" enclose=none>CounterVariable</source>. The code block associated with the loop is identified by a colon and indenting as described above. | ||
− | There are various ways of creating a Python | + | There are various ways of creating a list in Python. The <source lang="python" enclose=none>range</source> function can be used to create sequences of numbers 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, use <source lang="python" enclose=none>range(1,11,3)</source>. Note that the stop value passed to the range function is not included in the list, i.e. <source lang="python" enclose=none>range(1,10,3)</source> would produce only the three numbers 1, 4 & 7. We can verify this at the Python command prompt, i.e. |
− | + | <source lang="python">>>> range(1,11,3) | |
+ | [1, 4, 7, 10] | ||
+ | >>> range(1,10,3) | ||
+ | [1, 4, 7] | ||
+ | </source> | ||
− | + | Python lists can also be created from a sequence of values separated by commas within square brackets, e.g. <source lang="python" enclose=none>MyList = [1.0, "hello", 1]</source> creates a list called <source lang="python" enclose=none>MyList</source> containing 3 values, a floating point number <source lang="python" enclose=none>1.0</source>, the string <source lang="python" enclose=none>hello</source> and an integer <source lang="python" enclose=none>1</source>. This example demonstrates that Python lists are general purpose containers, and that 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 <source lang="python" enclose=none>while</source> keyword, so | Conditional while loops are identified with the <source lang="python" enclose=none>while</source> keyword, so | ||
Line 75: | Line 79: | ||
... | ... | ||
</source> | </source> | ||
− | will repeatedly execute the code block for as long as <source lang="python" enclose=none>condition</source> is | + | will repeatedly execute the code block for as long as <source lang="python" enclose=none>condition</source> is <source lang="python" enclose=none>True</source>. |
+ | |||
+ | As in MATLAB, Python allows us to break out of for or while loops, or continues with the next iteration of a loop, using <source enclose=none lang="python">break</source> and <source enclose=none lang="python">continue</source> respectively. | ||
== <source lang="python" enclose=none>for </source> == | == <source lang="python" enclose=none>for </source> == | ||
− | We now look at the Python equivalents of the MATLAB code discussed in [[Program_Flow_and_Logicals]] | + | We now look at the Python equivalents of the MATLAB code discussed in the [[Program_Flow_and_Logicals#for_..._end_loop|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 <source enclose=none lang="python">e</source> are known in advance, the Python version of the algorithm is: |
+ | |||
+ | # Find length of the list containing the error terms <source enclose=none lang="python">e</source>: <source lang="python" enclose=none>T=len(e)</source> | ||
+ | # Initialize a list <source enclose=none lang="python">y</source> with the same length as vector <source enclose=none lang="python">e</source>: <source enclose=none lang="python">y=[0.0]*T</source> | ||
+ | # Compute <source enclose=none lang="python">y[0]=phi0+phi1*y0+e[0]</source>. Please remember, we assume that <math>y_0=E(y)=\phi_0/(1-\phi_1)</math> | ||
+ | # Compute <source enclose=none lang="python">y[i]=phi0+phi1*y[i-1]+e[i]</source> for <math>i=1</math> | ||
+ | # Repeat line 4 for <math>i=2,...,(T-1)</math> | ||
+ | |||
+ | A simple implementation in Python is | ||
+ | |||
+ | <source lang="python">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] | ||
+ | </source> | ||
+ | |||
+ | and for comparison the MATLAB code is | ||
<source> T=size(e,1); | <source> T=size(e,1); | ||
Line 89: | Line 113: | ||
end</source> | end</source> | ||
− | |||
− | <source lang="python"> | + | One difference to note is Python list and array indexing starts at 0 and uses square brackets, whereas array indices start at 1 in MATLAB. The line <source lang="python" enclose=none>y=[0.0]*T</source> preallocates a Python list containing <source lang="python" enclose=none>T</source> floating point numbers all set to zero. |
− | y=[0.]*T | + | |
− | |||
− | |||
− | |||
− | |||
− | </source> | ||
− | |||
== <source lang="python" enclose=none>if else</source> == | == <source lang="python" enclose=none>if else</source> == | ||
+ | |||
+ | As above, a description of the mathematics can be found on the [[Program_Flow_and_Logicals#if_else_end_or_if_end|MATLAB page on Program Flow and Logicals]]. The Python algorithm is now | ||
+ | |||
+ | # Find length of the list containing the error terms <source enclose=none lang="python">e</source>: <source lang="python" enclose=none>T=len(e)</source> | ||
+ | # Initialize a list <source enclose=none lang="python">y</source> with the same length as <source enclose=none lang="python">e</source>: <source enclose=none lang="python">y=[0.0]*T</source> | ||
+ | # Check whether <source enclose=none lang="python">abs(phi1)<1</source>. If this statement is true, then <source enclose=none lang="python">y0=phi0/(1-phi1)</source>. Else, <source enclose=none lang="python">y0=0</source>. Please remember, we set <math>y_0=E(y_0)</math>. | ||
+ | # Compute <source enclose=none lang="python">y[0]=phi0+phi1*y0+e[0]</source>. | ||
+ | # Compute <source enclose=none lang="python">y[i]=phi0+phi1*y[i-1]+e[i]</source> for <math>i=1</math> | ||
+ | # Repeat line 5 for <math>i=2,...,(T-1)</math> | ||
== <source lang="python" enclose=none>while</source> == | == <source lang="python" enclose=none>while</source> == |
Revision as of 10:32, 10 October 2013
Contents
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, Python uses a change in indent. 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.
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 the 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 CounterVariable in ListOfValues:
statement1
statement2
...
and repeat for as many times as there are elements in the ListOfValues
, each time assigning the next element in the list to the CounterVariable
. 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 numbers 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, 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]
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 that 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 continues 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:
- Find length of the list containing the error terms
e
:T=len(e)
- Initialize a list
y
with the same length as vectore
:y=[0.0]*T
- Compute
y[0]=phi0+phi1*y0+e[0]
. Please remember, we assume that [math]y_0=E(y)=\phi_0/(1-\phi_1)[/math] - Compute
y[i]=phi0+phi1*y[i-1]+e[i]
for [math]i=1[/math] - Repeat line 4 for [math]i=2,...,(T-1)[/math]
A simple implementation in Python is
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 difference to note is Python list and array indexing starts at 0 and uses square brackets, whereas array indices start at 1 in MATLAB. The line y=[0.0]*T
preallocates a Python list containing T
floating point numbers all set to zero.
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
- Find length of the list containing the error terms
e
:T=len(e)
- Initialize a list
y
with the same length ase
:y=[0.0]*T
- Check whether
abs(phi1)<1
. If this statement is true, theny0=phi0/(1-phi1)
. Else,y0=0
. Please remember, we set [math]y_0=E(y_0)[/math]. - Compute
y[0]=phi0+phi1*y0+e[0]
. - Compute
y[i]=phi0+phi1*y[i-1]+e[i]
for [math]i=1[/math] - Repeat line 5 for [math]i=2,...,(T-1)[/math]