This tutorial primerily consists of a modified version of the lecture by J.R. Johansson (robert@riken.jp) http://dml.riken.jp/~rob/.
The latest version of the original IPython notebook lecture is available at http://github.com/jrjohansson/scientific-python-lectures.
Prerequisites: No prerequisites.
NOTE: This and the original material are copyrighted. For any additional details, please refer to the LICENSE and to the original repository.
Python is a modern, general-purpose, object-oriented, high-level programming language.
General characteristics of Python:
Technical details:
Advantages:
Disadvantages:
Python has a strong position in scientific computing:
Extensive ecosystem of scientific libraries and environments
Great performance due to close integration with time-tested and highly optimized codes written in C and Fortran:
Good support for
Readily available and suitable for use on high-performance computing clusters.
No license costs, no unnecessary use of research budget.
The iPython Notebook has several useful shortcuts that can save you a lot of time. To see the list of available shortcuts press ctrl-m + h.
Python code is usually stored in text files with the file ending ".py
":
myprogram.py
Every line in a Python program file is assumed to be a Python statement, or part thereof.
#
(optionally preceded by an arbitrary number of white-space characters, i.e., tabs or spaces). Comment lines are usually ignored by the Python interpreter.To run our Python program from the command line we use:
$ python myprogram.py
On UNIX systems it is common to define the path to the interpreter on the first line of the program (note that this is a comment line as far as the Python interpreter is concerned):
#!/usr/bin/env python
If we do, and if we additionally set the file script to be executable, we can run the program like this:
$ myprogram.py
ls scripts/hello-world*.py
scripts/hello-world-in-arabic.py scripts/hello-world.py
cat scripts/hello-world.py
#!/usr/bin/env python print("Hello world!")
!python scripts/hello-world.py
Hello world!
The standard character encoding is ASCII, but we can use any other encoding, for example UTF-8. To specify that UTF-8 is used we include the special line
# -*- coding: UTF-8 -*-
at the top of the file.
cat scripts/hello-world-in-arabic.py
#!/usr/bin/env python #-*- coding: utf-8 -*- print("مرحبا")
!python scripts/hello-world-in-arabic.py
مرحبا
Other than these two optional lines in the beginning of a Python code file, no additional code is required for initializing a program.
This file - an IPython notebook - does not follow the standard pattern with Python code in a text file. Instead, an IPython notebook is stored as a file in the JSON format. The advantage is that we can mix formatted text, Python code and code output. It requires the IPython notebook server to run it though, and therefore isn't a stand-alone Python program as described above. Other than that, there is no difference between the Python code that goes into a program file or an IPython notebook.
Most of the functionality in Python is provided by modules. The Python Standard Library is a large collection of modules that provides cross-platform implementations of common facilities such as access to the operating system, file I/O, string management, network communication, and much more.
To use a module in a Python program it first has to be imported. A module can be imported using the import
statement. For example, to import the module math
, which contains many standard mathematical functions, we can do:
import math
This includes the whole module and makes it available for use later in the program. For example, we can do:
import math
x = math.cos(2 * math.pi)
print(x)
1.0
Alternatively, we can chose to import all symbols (functions and variables) in a module to the current namespace (so that we don't need to use the prefix "math.
" every time we use something from the math
module:
from math import *
x = cos(2 * pi)
print(x)
1.0
This pattern can be very convenient, but in large programs that include many modules it is often a good idea to keep the symbols from each module in their own namespaces, by using the import math
pattern. This would elminate potentially confusing problems with name space collisions.
As a third alternative, we can chose to import only a few selected symbols from a module by explicitly listing which ones we want to import instead of using the wildcard character *
:
from math import cos, pi
x = cos(2 * pi)
print(x)
1.0
It is also possible to rename the function or the imported module
from math import cos as cos1
import math as ma
x = cos1(2 * ma.pi)
print(x)
1.0
Once a module is imported, we can list the symbols it provides using the dir
function:
import math
print(dir(math))
['__doc__', '__file__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'hypot', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']
And using the function help
we can get a description of each function (almost .. not all functions have docstrings, as they are technically called, but the vast majority of functions are documented this way).
help(math.log)
Help on built-in function log in module math: log(...) log(x[, base]) Return the logarithm of x to the given base. If the base not specified, returns the natural logarithm (base e) of x.
log(10)
2.302585092994046
log(10, 2)
3.3219280948873626
We can also use the help
function directly on modules: Try
help(math)
Some very useful modules form the Python standard library are os
, sys
, math
, shutil
, re
, subprocess
, multiprocessing
, threading
.
A complete lists of standard modules for Python 2 and Python 3 are available at http://docs.python.org/2/library/ and http://docs.python.org/3/library/, respectively.
The os
module contains a function named getcwd
. Find out what this functions do and print its output
%load solutions/getting_help.py
from os import getcwd
help(getcwd)
print(getcwd())
Variable names in Python can contain alphanumerical characters a-z
, A-Z
, 0-9
and some special characters such as _
. Normal variable names must start with a letter.
By convension, variable names start with a lower-case letter, and Class names start with a capital letter.
In addition, there are a number of Python keywords that cannot be used as variable names. These keywords are:
and, as, assert, break, class, continue, def, del, elif, else, except,
exec, finally, for, from, global, if, import, in, is, lambda, not, or,
pass, print, raise, return, try, while, with, yield
Note: Be aware of the keyword lambda
, which could easily be a natural variable name in a scientific program. But being a keyword, it cannot be used as a variable name.
The assignment operator in Python is =
. Python is a dynamically typed language, so we do not need to specify the type of a variable when we create one.
Assigning a value to a new variable creates the variable:
# variable assignments
x = 1.0
my_variable = 12.2
Although not explicitly specified, a variable do have a type associated with it. The type is derived form the value it was assigned.
type(x)
float
If we assign a new value to a variable, its type can change.
x = 1
type(x)
int
If we try to use a variable that has not yet been defined we get an NameError
:
print(y)
--------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-20-36b2093251cd> in <module>() ----> 1 print(y) NameError: name 'y' is not defined
# integers
x = 1
type(x)
int
# float
x = 1.0
type(x)
float
# boolean
b1 = True
b2 = False
type(b1)
bool
# complex numbers: note the use of `j` to specify the imaginary part
x = 1.0 - 1.0j
type(x)
complex
print(x)
(1-1j)
print(x.real, x.imag)
(1.0, -1.0)
The module types
contains a number of type name definitions that can be used to test if variables are of certain types:
import types
# print all types defined in the `types` module
print(dir(types))
['BooleanType', 'BufferType', 'BuiltinFunctionType', 'BuiltinMethodType', 'ClassType', 'CodeType', 'ComplexType', 'DictProxyType', 'DictType', 'DictionaryType', 'EllipsisType', 'FileType', 'FloatType', 'FrameType', 'FunctionType', 'GeneratorType', 'GetSetDescriptorType', 'InstanceType', 'IntType', 'LambdaType', 'ListType', 'LongType', 'MemberDescriptorType', 'MethodType', 'ModuleType', 'NoneType', 'NotImplementedType', 'ObjectType', 'SliceType', 'StringType', 'StringTypes', 'TracebackType', 'TupleType', 'TypeType', 'UnboundMethodType', 'UnicodeType', 'XRangeType', '__builtins__', '__doc__', '__file__', '__name__', '__package__']
x = 1.0
# check if the variable x is a float
type(x) is float
True
# check if the variable x is an int
type(x) is int
False
We can also use the isinstance
method for testing types of variables:
isinstance(x, float)
True
x = 1.5
print(x, type(x))
(1.5, <type 'float'>)
x = int(x)
print(x, type(x))
(1, <type 'int'>)
z = complex(x)
print(z, type(z))
((1+0j), <type 'complex'>)
x = float(z)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-34-e719cc7b3e96> in <module>() ----> 1 x = float(z) TypeError: can't convert complex to float
Complex variables cannot be cast to floats or integers. We need to use z.real
or z.imag
to extract the part of the complex number we want:
y = bool(z.real)
print(z.real, " -> ", y, type(y))
y = bool(z.imag)
print(z.imag, " -> ", y, type(y))
(1.0, ' -> ', True, <type 'bool'>) (0.0, ' -> ', False, <type 'bool'>)
Most operators and comparisons in Python work as one would expect:
+
, -
, *
, /
, //
(integer division), '**' power1 + 2, 1 - 2, 1 * 2, 1 / 2
(3, -1, 2, 0)
1.0 + 2.0, 1.0 - 2.0, 1.0 * 2.0, 1.0 / 2.0
(3.0, -1.0, 2.0, 0.5)
# Integer division of float numbers
3.0 // 2.0
1.0
# Note! The power operators in python isn't ^, but **
2 ** 2
4
and
, not
, or
.True and False
False
not False
True
True or False
True
>
, <
, >=
(greater or equal), <=
(less or equal), ==
equality, !=
inequality, is
identical.2 > 1, 2 < 1
(True, False)
2 > 2, 2 < 2
(False, False)
2 >= 2, 2 <= 2
(True, True)
# equality
[1,2] == [1,2]
True
# inequality
1 != 1
False
# objects identical?
l1 =[1,2]
l2 = l1
l1 is l2
True
Use Python to evaluate the following expression, for the given variables' values, to get the correct results and print the output
(5 * (a>b) + 2 * (a<b*4) ) / a * c
Note: you will need to use some variables casting
a = 15
b = 5
c = 2.2
# expression evaluation here
val = 0
print(val)
0
%load solutions/operators.py
a = 15
b = 5
c = 2.2
# expression evaluation here
val = (float(5*(a>b)) + float(2*(a<(b*4))))/float(a) * c
print(val)
s = "Hello world"
type(s)
str
s1 = "KAUST's hello world"
print(s1)
s2 = 'He said "Hello"'
print(s2)
KAUST's hello world He said "Hello"
# length of the string: the number of characters
len(s)
11
# replace a substring in a string with somethign else
s2 = s.replace("world", "test")
print(s2)
Hello test
We can index a character in a string using []
:
s[0]
'H'
Heads up MATLAB users: Indexing start at 0!
We can extract a part of a string using the syntax [start:stop]
, which extracts characters between index start
and stop
:
s[0:5]
'Hello'
If we omit either (or both) of start
or stop
from [start:stop]
, the default is the beginning and the end of the string, respectively:
s[:5]
'Hello'
s[6:]
'world'
s[:]
'Hello world'
s[:-2]
'Hello wor'
s[-1], s[-2]
('d', 'l')
We can also define the step size using the syntax [start:end:step]
(the default value for step
is 1, as we saw above):
s[::1]
'Hello world'
s[::2]
'Hlowrd'
This technique is called slicing. Read more about the syntax here: http://docs.python.org/release/2.7.3/library/functions.html?highlight=slice#slice
Some examples of this subsection are brought from http://docs.python.org/2/tutorial/inputoutput.html
Many operations can be performed over the strings in python. The following command shows the available string operations provided by str objects.
print(dir(str))
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
Here we will look at rjust
, format
, zfill
, and using the %
operator for c-style formatting.
The following code shows an example of using the c-style formatting. More formatting specifiers can be found in a c language documentation. A good source: http://www.cplusplus.com/reference/cstdio/printf/.
import math
print 'The value of %5s is approximately %5.3f.' % ('PI', math.pi)
The value of PI is approximately 3.142.
The zfill
function pads the given number with zeros from the left to reach the desired width of the number
print('1234'.zfill(7))
print('-3.14'.zfill(7))
print('1234'.zfill(2))
0001234 -003.14 1234
The rjust
command pads a given string from the left, using spaces by default, to reach the desired width. The following example shows how this function can be used to print tables in pretty way.
print str(1).rjust(2), str(1**2).rjust(3),str(1**3).rjust(4)
print str(5).rjust(2), str(5**2).rjust(3),str(5**3).rjust(4)
print str(10).rjust(2), str(10**2).rjust(3),str(10**3).rjust(4)
1 1 1 5 25 125 10 100 1000
The following code shows examples of using the format
function to control the formatting of the input values to the string
print('We are the {} who say "{}!"'.format('knights', 'Ni'))
We are the knights who say "Ni!"
print('{0} and {1}'.format('spam', 'eggs'))
print('{1} and {0}'.format('spam', 'eggs'))
spam and eggs eggs and spam
print( 'This {food} is {adjective}.'.format(food='spam', adjective='absolutely horrible') )
This spam is absolutely horrible.
print( 'The story of {0}, {1}, and {other}.'.format('Bill', 'Manfred', other='Georg') )
The story of Bill, Manfred, and Georg.
import math
print( 'The value of PI is approximately {0:.3f}.'.format(math.pi) )
The value of PI is approximately 3.142.
name1 = 'Sjoerd'
phone1 = 4127
name2 = 'Jack'
phone2 = 4098
name3 = 'Dcab'
phone3 = 7678
print( '{0:10} ==> {1:10d}'.format(name1, phone1) )
print( '{0:10} ==> {1:10d}'.format(name2, phone2) )
print( '{0:10} ==> {1:10d}'.format(name3, phone3) )
Sjoerd ==> 4127 Jack ==> 4098 Dcab ==> 7678
Python has a very rich set of functions for text processing. See for example http://docs.python.org/2/library/string.html for more information.
Use string built-in functions and sliding operation to perform the following over the text of Hello world
o
with a
. (Hint: use the 'replace' built-in function in the string)
%load solutions/strings.py
s = 'Hello world'
s = s.replace('o', 'a')
s = s[:6].lower() + s[6:].upper()
print(s[3:-1])
Lists are very similar to strings, except that each element can be of any type.
The syntax for creating lists in Python is [...]
:
l = [1,2,3,4]
print(type(l))
print(l)
<type 'list'> [1, 2, 3, 4]
We can use the same slicing techniques to manipulate lists as we could use on strings:
print(l)
print(l[1:3])
print(l[::2])
[1, 2, 3, 4] [2, 3] [1, 3]
Heads up MATLAB users: Indexing starts at 0!
l[0]
1
Elements in a list do not all have to be of the same type:
l = [1, 'a', 1.0, 1-1j]
print(l)
[1, 'a', 1.0, (1-1j)]
Python lists can be inhomogeneous and arbitrarily nested:
nested_list = [1, [2, [3, [4, [5]]]]]
print(nested_list)
[1, [2, [3, [4, [5]]]]]
Accessing elements in nested lists
nl = [1, [2, 3, 4], [5, [6, 7, 8]]]
print(nl)
print(nl[0])
print(nl[1][1])
print(nl[2][1][2])
[1, [2, 3, 4], [5, [6, 7, 8]]] 1 3 8
Lists play a very important role in Python, and are for example used in loops and other flow control structures (discussed below). There are number of convenient functions for generating lists of various types, for example the range
function:
start = 10
stop = 30
step = 2
range(start, stop, step)
[10, 12, 14, 16, 18, 20, 22, 24, 26, 28]
# in python 3 range generates an interator, which can be converted to a list using 'list(...)'. It has no effect in python 2
list(range(start, stop, step))
[10, 12, 14, 16, 18, 20, 22, 24, 26, 28]
list(range(-10, 10))
[-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
s
'Hello world'
# convert a string to a list by type casting:
s2 = list(s)
s2
['H', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
# sorting lists
s2.sort()
print(s2)
[' ', 'H', 'd', 'e', 'l', 'l', 'l', 'o', 'o', 'r', 'w']
# create a new empty list
l = []
# add an elements using `append`
l.append("A")
l.append("d")
l.append("d")
print(l)
['A', 'd', 'd']
We can modify lists by assigning new values to elements in the list. In technical jargon, lists are mutable.
l[1] = "p"
l[2] = "p"
print(l)
['A', 'p', 'p']
l[1:3] = ["d", "d"]
print(l)
['A', 'd', 'd']
Insert an element at an specific index using insert
l.insert(0, "i")
l.insert(1, "n")
l.insert(2, "s")
l.insert(3, "e")
l.insert(4, "r")
l.insert(5, "t")
print(l)
['i', 'n', 's', 'e', 'r', 't', 'A', 'd', 'd']
Remove first element with specific value using 'remove'
l.remove("A")
print(l)
['i', 'n', 's', 'e', 'r', 't', 'd', 'd']
Remove an element at a specific location using del
:
del l[7]
del l[6]
print(l)
['i', 'n', 's', 'e', 'r', 't']
Using operators with lists
l1 = [1, 2, 3] + [4, 5, 6]
print(l1)
l2 = [1, 2, 3] * 2
print(l2)
[1, 2, 3, 4, 5, 6] [1, 2, 3, 1, 2, 3]
By default Python copies lists by reference as we can see in the following example
a = [1, 2, 3]
b = a
print("a is b? ", a is b)
b[0] = -1
print("a = ", a)
print("b = ", b)
('a is b? ', True) ('a = ', [-1, 2, 3]) ('b = ', [-1, 2, 3])
To copy the array by value we can do the following
a = [1, 2, 3]
b = a[:] # or:
print("a is b? ", a is b)
c = list(a)
b[0] = -1
c[1] = -1
print("a = ", a)
print("b = ", b)
print("c = ", c)
('a is b? ', False) ('a = ', [1, 2, 3]) ('b = ', [-1, 2, 3]) ('c = ', [1, -1, 3])
This method does not work when the list contains lists
a = [ [1, 2, 3], 4, 5]
b = a[:]
c = list(a)
a[0].append(-1)
print("a = ", a)
print("b = ", b)
print("c = ", c)
('a = ', [[1, 2, 3, -1], 4, 5]) ('b = ', [[1, 2, 3, -1], 4, 5]) ('c = ', [[1, 2, 3, -1], 4, 5])
The solution here is to use the copy module
from copy import deepcopy
a = [ [1, 2, 3], 4, 5]
b = deepcopy(a)
a[0].append(-1)
print("a = ", a)
print("b = ", b)
('a = ', [[1, 2, 3, -1], 4, 5]) ('b = ', [[1, 2, 3], 4, 5])
See help(list)
for more details, or read the online documentation
Perform the following list operations and print the final output
-1
Hello
after the first element
%load solutions/lists.py
l = range(5,16,2)
print(l)
l[-1] = range(4,9,2)
print(l)
l[-1][-2] = -1
print(l)
del l[1:4]
print(l)
l.insert(1, 'Hello')
print(l)
Tuples are like lists, except that they cannot be modified once created, that is they are immutable.
In Python, tuples are created using the syntax (..., ..., ...)
, or even ..., ...
:
point = (10, 20)
print(point, type(point))
((10, 20), <type 'tuple'>)
point = 10, 20
print(point, type(point))
((10, 20), <type 'tuple'>)
We can unpack a tuple by assigning it to a comma-separated list of variables:
x, y = point
print("x =", x)
print("y =", y)
('x =', 10) ('y =', 20)
If we try to assign a new value to an element in a tuple we get an error:
point[0] = 20
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-102-ac1c641a5dca> in <module>() ----> 1 point[0] = 20 TypeError: 'tuple' object does not support item assignment
Dictionaries are also like lists, except that each element is a key-value pair. The syntax for dictionaries is {key1 : value1, ...}
:
params = {"parameter1" : 1.0,
"parameter2" : 2.0,
"parameter3" : 3.0,
1: 4.0,
(5, 'ho'): 'hi'}
print(type(params))
print(params)
<type 'dict'> {1: 4.0, 'parameter1': 1.0, (5, 'ho'): 'hi', 'parameter3': 3.0, 'parameter2': 2.0}
print("parameter1 = " + str(params["parameter1"]))
print("parameter2 = " + str(params["parameter2"]))
print("parameter3 = " + str(params["parameter3"]))
parameter1 = 1.0 parameter2 = 2.0 parameter3 = 3.0
params["parameter1"] = "A"
params["parameter2"] = "B"
# add a new entry
params["parameter4"] = "D"
print("parameter1 = " + str(params["parameter1"]))
print("parameter2 = " + str(params["parameter2"]))
print("parameter3 = " + str(params["parameter3"]))
print("parameter4 = " + str(params["parameter4"]))
print("'key 1' = " + str(params[1]))
print("'key (5, 'ho')' = " + str(params[(5, 'ho')]))
parameter1 = A parameter2 = B parameter3 = 3.0 parameter4 = D 'key 1' = 4.0 'key (5, 'ho')' = hi
del params["parameter2"]
print(params)
{'parameter4': 'D', 'parameter1': 'A', 'parameter3': 3.0, 1: 4.0, (5, 'ho'): 'hi'}
Create a dictionary that uses a tuple of the first and last name of the person as a key and his/her corresponding age as a value for the following list of people
Perform the following updates to the dictionary
%load solutions/dicts.py
d = {('John', 'Smith'):30,
('Ahmad', 'Said'):22,
('Sara', 'John'):2
}
print(d)
john = ('John', 'Smith')
d[john] = d[john] + 1
print(d)
d[('Ahmad', 'Ahmad')] = 19
print(d)
del d[('Sara','John')]
print(d)
The Python syntax for conditional execution of code use the keywords if
, elif
(else if), else
:
statement1 = False
statement2 = False
if statement1:
print("statement1 is True")
elif statement2:
print("statement2 is True")
else:
print("statement1 and statement2 are False")
statement1 and statement2 are False
For the first time, here we encounted a peculiar and unusual aspect of the Python programming language: Program blocks are defined by their indentation level.
Compare to the equivalent C code:
if (statement1)
{
printf("statement1 is True\n");
}
else if (statement2)
{
printf("statement2 is True\n");
}
else
{
printf("statement1 and statement2 are False\n");
}
In C blocks are defined by the enclosing curly brakets {
and }
. And the level of indentation (white space before the code statements) does not matter (completely optional).
But in Python, the extent of a code block is defined by the indentation level (usually a tab or say four white spaces). This means that we have to be careful to indent our code correctly, or else we will get syntax errors.
Examples:
statement1 = statement2 = True
if statement1:
if statement2:
print("both statement1 and statement2 are True")
both statement1 and statement2 are True
# Bad indentation!
if statement1:
if statement2:
print("both statement1 and statement2 are True") # this line is not properly indented
File "<ipython-input-110-78979cdecf37>", line 4 print("both statement1 and statement2 are True") # this line is not properly indented ^ IndentationError: expected an indented block
statement1 = False
if statement1:
print("printed if statement1 is True")
print("still inside the if block")
x = 10
y = 5
if x > y:
print(float(x)/y)
elif x == y:
print(1)
else:
print(float(y)/x)
if statement1:
print("printed if statement1 is True")
print("now outside the if block")
# a compact way for using the if statement
a = 2 if statement1 else 4
print("a= ", a)
name = 'john'
if name in ['jed', 'john']:
print("We have Jed or John")
num = 1
if num in [1, 2]:
print("We have 1 or 2")
In Python, loops can be programmed in a number of different ways. The most common is the for
loop, which is used together with iterable objects, such as lists. The basic syntax is:
for
loops:
for x in [1,2,3]:
print(x)
The for
loop iterates over the elements of the supplied list, and executes the containing block once for each element. Any kind of list can be used in the for
loop. For example:
for x in range(4): # by default range start at 0
print(x)
Note: range(4)
does not include 4 !
for x in range(-3,3):
print(x)
for word in ["scientific", "computing", "with", "python"]:
print(word)
To iterate over key-value pairs of a dictionary:
for key, value in params.items():
print(key + " = " + str(value))
Sometimes it is useful to have access to the indices of the values when iterating over a list. We can use the enumerate
function for this:
for idx, x in enumerate(range(-3,3)):
print(idx, x)
List comprehensions: Creating lists using for
loops:
A convenient and compact way to initialize lists:
l1 = [x**2 for x in range(0,5)]
print(l1)
# Nested list comprehensions
l2 = [(x, y) for x in range(0,5) for y in range(5,10)]
print(l2)
#List comprehensions with conditional statement
l1 = [x**2 for x in range(0,5) if x != 2]
print(l1)
while
loops:
i = 0
while i < 5:
print(i)
i = i + 1
print("done")
Note that the print("done")
statement is not part of the while
loop body because of the difference in indentation.
Loop through the following list of words and create a dictionary according to the following rules:
words = ["Aerial", "Affect", "Agile", "Agriculture", "Animal", "Attract", "Audubon",
"Backyard", "Barrier", "Beak", "Bill", "Birdbath", "Branch", "Breed", "Buzzard",
"The", "On", "Upper", "Not", "What", "Linked", "Up", "In", "A", "lol"]
%load solutions/control_flow.py
d = {}
for w in words:
if len(w) > 2:
if len(w) in d:
d[len(w)].append(w)
else:
d[len(w)] = [w]
print d
A function in Python is defined using the keyword def
, followed by a function name, a signature within parentheses ()
, and a colon :
. The following code, with one additional level of indentation, is the function body.
def func0():
print("test")
func0()
Optionally, but highly recommended, we can define a so called "docstring", which is a description of the functions purpose and behaivor. The docstring should follow directly after the function definition, before the code in the function body.
def func1(s):
"""
Print a string 's' and tell how many characters it has
"""
print(s + " has " + str(len(s)) + " characters")
help(func1)
func1("test")
Functions that returns a value use the return
keyword:
def square(x):
"""
Return the square of x.
"""
return x ** 2
square(4)
We can return multiple values from a function using tuples (see above):
def powers(x):
"""
Return a few powers of x.
"""
return x ** 2, x ** 3, x ** 4
powers(3)
x2, x3, x4 = powers(3)
print(x3)
In a definition of a function, we can give default values to the arguments the function takes:
def myfunc(x, p=2, debug=False):
if debug:
print("evaluating myfunc for x = " + str(x) + " using exponent p = " + str(p))
return x**p
If we don't provide a value of the debug
argument when calling the the function myfunc
it defaults to the value provided in the function definition:
myfunc(5)
myfunc(5, debug=True)
If we explicitly list the name of the arguments in the function calls, they do not need to come in the same order as in the function definition. This is called keyword arguments, and is often very useful in functions that takes a lot of optional arguments.
myfunc(p=3, debug=True, x=7)
In Python we can also create unnamed functions, using the lambda
keyword:
f1 = lambda x: x**2
# is equivalent to
def f2(x):
return x**2
f1(2), f2(2)
This technique is useful for exmample when we want to pass a simple function as an argument to another function, like this:
# map is a built-in python function
map(lambda x: x**2, range(-3,4))
# in python 3 we can use `list(...)` to convert the iterator to an explicit list
list(map(lambda x: x**2, range(-3,4)))
Write function called apply
which does the same thing as map
does: It should take a list and a function as an argument, and returns a list with values that returned by the provided function applied to the list elements. Test it on a provided list and use a lambda function that takes an element and returns its absolute value.
elements = [-100, 21, 115, 0.34, 45, -80, 12, 120, 73, -1]
%load solutions/functions.py
def apply(l, fun):
new_l = []
for el in l:
new_l.append(fun(el))
return new_l
apply(elements, lambda x: abs(x))
Regular expressions are special sequences of symbol that are used in various pattern matching tasks. They are extremely useful, and can help save a bunch of time when we are trying to parse text files. Below, we will learn the most essintial things about regular expressions in Pyhton on a few examples. For more details see the documentation.
import re # Regular expression functionality of Python is placed in a separate module 're'
string = 'Hello, class! This is a testing string that contains a word CAT'
pattern = r'CAT'
match = re.search(pattern, string)
if match:
print 'found', match.group()
else:
print 'not found'
found CAT
Most often we don't have particular and precise patterns we need to match. Instead, we have fuzzy definitions, different word forms, etc., and this is exactly where regular expressions save our time.
string = 'Hello, class! This is a testing string that contains a word caT'
pat = r'[cC][aA][tT]'
print 'found', re.search(pat, string).group()
found caT
The basic syntax of regular expressions:
# Special characters: . ^ $ * + ? { } [ ] \ | ( )
string = 'Hello, class! This is a testing string that contains a word CAR'
pat = 'CA.'
print 'found', re.search(pat, string).group()
found CAR
string = 'Hello, class! This is a testing string that contains a word CAAAAAAAAAAAT'
pat = 'CA*T'
print 'found', re.search(pat, string).group()
found CAAAAAAAAAAAT
string = 'Hello, class! This is a testing string that contains a word CAAT'
pat = 'CA+T'
print 'found', re.search(pat, string).group()
found CAAT
Now, if we need to search some pattern multiple times, it is more efficient to 'compile' it first, and then use it.
pat = re.compile(r'CA+T')
print 'found', pat.search(string).group()
found CAAT
# Yet another example
line = "Cats are smarter than dogs"
matchObj = re.match( r'(.*) are (.*?) .*', line)
if matchObj:
print "matchObj.group() : ", matchObj.group()
print "matchObj.group(1) : ", matchObj.group(1)
print "matchObj.group(2) : ", matchObj.group(2)
else:
print "No match!!"
matchObj.group() : Cats are smarter than dogs matchObj.group(1) : Cats matchObj.group(2) : smarter
dir(pat)
['__class__', '__copy__', '__deepcopy__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'findall', 'finditer', 'flags', 'groupindex', 'groups', 'match', 'pattern', 'scanner', 'search', 'split', 'sub', 'subn']
pat.findall?
We are ready to use now regular expressions in more common way, and show its power.
# A piece of text from "KAUST Highlights of 2013" article
text = """
This past year saw members of KAUST faculty and leadership being awarded major international awards.
At the beginning of the year, Prof. Jean Frechet, KAUST Vice President for Research, was awarded the 2013 Japan
Prize in recognition of his original and outstanding scientific achievements serving to promote peace and prosperity
for all mankind. Dr. Frechet and C. Grant Willson of the University of Texas at Austin were recognized for their achievement
in the development of chemically amplified resistant polymer materials for innovative semiconductor manufacturing processes.
Also appointed in the past year, Prof. Yves Gnanou, KAUST Dean of Physical Science and Engineering (PSE), was inducted into
the elite ranks of the French Ordre national de la Légion d'honneur (National Order of the Legion of Honor). He was
presented with the coveted Chevalier medal at a ceremony held in Paris on June 27, 2013. Established over two centuries
ago by Napoleon Bonaparte, the award recognizes its recipients' extraordinary contributions to France and French culture.
Prof. Gnanou previously served as Vice President of Academic Affairs and Research at École Polytechnique in Paris. Spanning
a third continent, the Desert Research Institute (DRI), in the US, presented Nina Fedoroff, Distinguished Professor of Bioscience
and Director of the KAUST Center for Desert Agriculture, with the 2013 Nevada Medal. The award acknowledges outstanding achievements
in science and engineering. The DRI President, Dr. Stephen Wells, said: "In only a few decades Prof. Fedoroff's research
has helped stimulate a revolution in biology."
"""
pat = re.compile(r'awards?')
pat.findall(text)
['award', 'awards', 'award', 'award', 'award']
pat = re.compile(r'award[^\s,.!?:;]*')
pat.findall(text)
['awarded', 'awards', 'awarded', 'award', 'award']
findall
method allows us to nicely combine parsed results into groups. In order to do this, we need only to use parentheses.
pat = re.compile(r'(award)([^\s,.!?:;]*)')
pat.findall(text)
[('award', 'ed'), ('award', 's'), ('award', 'ed'), ('award', ''), ('award', '')]
Design a pattern that matches only correct email addresses. Apply this pattern to match all the emails in the provided string. Count the number of emails you got. Also make sure that your pattern's findall
returns groups of kind ('name', 'domain.com') excluding '@' symbol.
# Taken from somewhere from the web
emails ="""
litke@talktalk.net
owarne000s@talk21.com
seo@webindustry.co.uk
w0lfspirit32@hotmail.co.uk
robert.douglas3@virgin.net
dan@webindustry.co.uk
sasha_aitken@mail.ru
brian@tweddle1966.freeserve.co.uk
asmileiscatching@hotmail.com
sashalws@aol.com
ebbygraham372@hotmail.com
chnelxx@hotmail.com
choudhury.esaa@hotmail.co.uk
girishvishwasjoshi@gmail.com
mark.clynch@ntlworld.com
ssladmin@eskdalesaddlery.co.uk
owarnes.t21@btinternet.com
mgrahamhaulage@aol.com
beccababes@dsl.pipex.com
victor-2k7@hotmail.co.uk
kellybomaholly@hotmail.com
sugar@caton9108.freeserve.co.uk
paulapowley@btinternet.com
owarnes@talk21.com
lesleygodwin1@hotmail.com
nicolawinter4@hotmail.com
diwasbhattarai@yahoo.com
james.hutchinson@aggregate.com
margaret.howroyd@hotmail.com
tina.wane@tiscali.co.uk
lizzy26259495@yahoo.com
kennyspence53@hotmail.com
pedrovieira1@gmail.com
versivul@mail.ru
booom2012@mail.ru sin_0.8@mail.ru
kaplya71@mail.ru smirnova-s-s@mail.ru
325jm@mail.ru rasmyrik@mail.ru
tanya_tyurnina@mail.ru fedorova2006@inbox.ru
veniaminm77@mail.ru dimon_gushin@mail.ru
anna_shevchenko@list.ru belexovagalina@mail.ru
engelgardt_ledi_elena_01.11.77@mail.ru
kolzhanov92@mail.ru digital1q@mail.ru
"""
%load solutions/regular.py
pat = re.compile("([\w.-_]+)@([\w.-]+\.[a-z]+)")
email_list = pat.findall(emails)
print email_list[:3]
print "# of emails in the list is", len(email_list)
In Python errors are managed with a special language construct called "Exceptions". When errors occur exceptions can be raised, which interrupts the normal program flow and fallback to somewhere else in the code where the closest try-except statement is defined.
To generate an exception we can use the raise
statement, which takes an argument that must be an instance of the class BaseExpection
or a class derived from it.
raise Exception("description of the error")
A typical use of exceptions is to abort functions when some error condition occurs, for example:
def my_function(arguments):
if not verify(arguments):
raise Expection("Invalid arguments")
# rest of the code goes here
To gracefully catch errors that are generated by functions and class methods, or by the Python interpreter itself, use the try
and except
statements:
try:
# normal code goes here
except:
# code for error handling goes here
# this code is not executed unless the code
# above generated an error
For example:
try:
print("test")
# generate an error: the variable test is not defined
print(test)
except:
print("Caught an expection")
test Caught an expection
To get information about the error, we can access the Exception
class instance that describes the exception by using for example:
except Exception as e:
try:
print("test")
# generate an error: the variable test is not defined
print(test)
except Exception as e:
print("Caught an exception:" + str(e))
test Caught an exception:name 'test' is not defined
The os module contains the makedirs
function which creates a directory, but if the directory already exists an error is raised. The goal of this exercise is to create a function that creates a directory given its name and ignores the error if the directory already exist.
(Hint: the module errno
contains an exception named EEXIST
that corresponds to the OSError
that is raised when the directory already exists)
os.makedirs('mydir')
--------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-113-1be329d03f15> in <module>() ----> 1 os.makedirs('mydir') NameError: name 'os' is not defined
os.makedirs('mydir') # This will raise error because the directory already exist
%load solutions/exeptions.py
def ensure_dir(d):
import os, errno
try:
os.makedirs(d)
#except OSError as exc:
except Exception as exc:
if exc.errno == errno.EEXIST:
pass
else: raise
ensure_dir('mydir')
Copyright 2014, Tareq Malas and Maruan Al-Shedivat, ACM Student Members.