Python Primer
Python Primer
Introduction
3
In praise of Python
● Python is a dynamic, interpreted (bytecode-
compiled) language. There are no type declarations
of variables, parameters, functions, or methods in
source code. This makes the code short and
flexible, and you lose the compile-time type
checking of the source code. Python tracks the
types of all values at runtime and flags code that
does not make sense as it runs.
● An excellent way to see how Python code works is
to run the Python interpreter and type code right
into it.
5
Scientific Computing
• Science has traditionally consisted of two major disciplines,
theory and experimentation.
Mathematical Modelling
Most problems based on real life are often too complex and cannot
be solved using analytical techniques alone – without computational
methods and scientific computing techniques we would be greatly
limited to the types of modelling possible.
8
Why Python?
Python is a general-purpose programming language initially
developed by Guido van Rossum in the 1990s.
The name has nothing to do with the reptile!
Features:
(very) Simple to pick up language – easy to maintain
open-source and free language
multi-platform - available on Windows, Mac OS, Linux and
almost all operating systems (Android also)
used by Google, YouTube, Instagram, NASA, CERN, Disney, . . .
9
Finance
https://www.python.org/
16
https://docs.python.org/2/library/
17
Compiled Interpreted
Explicitly Explicitly Implicitly
Purely
compiled compiled compiled
interpreted
to machine to byte to byte
code code code
Distributions of Python
Python is a language, then there exist different distributions of
Python (Python official, Anaconda Python, Enthought Canopy,
pythonxy . . . ).
Python 2 or 3
Installation on Windows
22
Editing Environment
Click
24
Syntactic sugar
syntactic sugar is syntax within a programming
language that is designed to make things easier to
read or to express. It makes the language "sweeter"
for human use: things can be expressed more clearly,
more concisely, or in an alternative style that some
may prefer.
https://en.wikipedia.org/wiki/Syntactic_sugar
26
Python script
Python script is a set of instructions, written in the
Python language, that run in order and carry out a
series of commands.
27
Importing Modules
Command Line
30
Running Python
Windows prompt
Window command
Introductory blurb
> python
Python 2.7.10(default, Oct 21 2015, 17:08:47)
[MSC v.1500 64 bit (AMD64)] on win 32
Python prompt
31
Quitting Python
>>> exit()
>>> Ctrl + D
32
Python command
Hello, world!
>>>
Whitespace
Whitespace is meaningful in Python: especially
indentation and placement of newlines.
– Use a newline to end a line of code.
– No braces { } to mark blocks of code in Python… Use
consistent indentation instead.
● The first line with less indentation is outside of the
block.
The first line with more indentation starts a nested block
– Often a colon appears at the start of a new block. (e.g.
for function and class definitions.)
36
Assignment
To assign a value to a variable, we use the operator =
(not to be confused with ‘equal to’). It is evaluated
from right to left
name = “Riaz”
can be seen as name “Riaz”
and interpreted as ‘Riaz is assigned to the variable
name’.
37
Interactive on Canopy
Interactive on PowerShell
39
Python commands
Python “function”
Round brackets
― “parentheses”
print('Hello, world!')
Function’s “argument”
Defining strings
Strings can be defined using
● single quotes ' …. '
Python text
Quotation marks
'Hello, world!'
The body
of the text
Quotes?
print Command/statement
'print' Text/string
43
Manipulating Strings
strings defined using single and double quotes are identical
Modules
When a Python program starts it only has access to basic
functions and classes.
Most of the functionality in Python is provided by modules. The
Python Standard Library is a collection of modules that
provides cross-platform implementations of common facilities
such
• I/O
• Mathematics
• String manipulation
Use “import” to tell Python to load a module e.g.
>>> import math
Operations on Strings
Two strings can be joined/added together (concatenated) using
the + operator:
In [1]: "Hello, " + "Riaz!"
Out[1]: 'Hello, Riaz!'
Slicing
string[12]
47
Immutability
Class: string
Length: 13
Letters
str 13 H e l l o ,␣w o r l d !
49
Pure concatenation
>>> 'Hello,␣' + 'world!'
'Hello, world!'
'Hello, world!'
Single or double
"Hello, world!" quotes on input.
Create same
string object.
>>> print('Hello, ↵
✘
File "<stdin>", line 1
print('Hello,
^
SyntaxError: EOL while
scanning string literal “EOL”: End Of Line
56
\n Converted into a
single character.
str, ↵ w o r l d !
13 H e l l o
>>> len('Hello,\nworld!')
13 len() function: gives
the length of the object
57
The backslash
Special Ordinary \' '
\" "
Ordinary Special \n ↵
\t ⇥
58
\n Multiline strings
"Shoot all the blue jays you want, \nif you can
hit 'em, but remember it's a \nsin to kill a
mockingbird. \nThat was the only time I ever
heard Atticus say \nit was a sin to do something,
\nand I asked Miss Maudie about it."
>>> 'Hello,\nworld!'
'Hello\nworld'
Python uses \n to represent
line breaks in strings.
>>> '''Hello,
... world!'''
'Hello,\nworld!' "Hello,\nworld!"
'''Hello, """Hello,
world!''' world!"""
Same result:
str, ↵ w o r l d !
13 H e l l o
63
>>> message
'Hello, world!'
>>> type(message)
<class 'str'>
message str, ␣ w o r l d !
13 H e l l o
63
64
>>> type(G’day!')
>>> type(-62)
>>> type(pi)
>>> int('␣-100␣')
- 1 0 0␣
6 ␣str
-100
-100
int
>>> int('100-10')
✘
ValueError:
invalid literal for int() with base 10: '100-10'
66
Exercise 1.0
1. Write script to print the following 2. Create the following output
text (with the line breaks) and then
run the script. It is a tale
Told by an idiot, full of sound and fury,
coffee Signifying nothing.
café
caffè
Kaffee
3. Create a file called car.py and write a comment next to each line
explaining what it does in English
67
Exercise 1.1
4. Rewrite the code below with your personal details and run. You should
experiment with the two string formatting characters %s and %d
68
Exercise 1.2
5. This exercise is for experimenting with data input from the keyboard. You
will also notice a new character %r.
69
Control statements – Else and If
An if-statement creates what is called a "branch" in the code.
The if-statement tells the Python script, “if this boolean expression is
True, then run the code under it, otherwise skip it.“
The code under the if needs to be indented four spaces? A colon at the
end of a line is how you tell Python you are going to create a new
"block" of code, and then indenting four spaces tells Python what lines
of code are in that block. This is exactly the same thing you will do
with functions later. Not indenting will give an error.
70
Exercise 2.0
Look at the code below. Make sure you are happy with the logic. Add
more Boolean expressions and increase the complexity. Use some of
the earlier script to increase complexity.
71
Files
Input Output
.txt
.dat
.csv
Reading Writing
72
Writing to files
Opening files for writing:
1. First decide what to do if there is already a files with the same name.
2. If you want to delete the file and start from scratch, pass “w” as the second
argument to open(). Example: open(“myfile.txt”, “w”)
3. If you want to append text to that file, pass “a” as the second argument to
open(). Example: open(“myfile.txt”, “a”)
Writing data:
print has a special syntax causing its output to be redirected to a file:
print >> file_object, comma_separated_expressions
Example:
75
Numbers in Python
A number can be represented by different types of variables:
int for integer
long integers for integer not in the previous interval. They are
stored in a more complex format. Such integers are printed out
with an L at the end:
4+8/2
✘ ✔
(4 + 8) / 2 4 + (8 / 2)
6 8
77
>>> float(10)
10.0
>>> int(10.9)
10 Truncates
fractional part
>>> int(-10.9)
-10
80
'10'
'10.0'
81
Integer arithmetic
>>> 10+5 >>> 25␣-␣5
15 10
Spaces around the
operator don’t matter.
>>> 20␣/␣3
6
84
Type-casting
>>> 20.0/3
6.666666666666667
>>> float(20/3)
6.0
85
Integer powers **
We wish to calculate 43
Integer remainders
Use “%” to obtain integer remainders
>>> 20%6
3
>>> -5␣%␣2
1 Remainder is always non-negative
87
>>> 4**2
16
>>> 16**2
256
>>> 256**2
65536
>>> 65536**2
4294967296
88
>>> 18446744073709551616**2
340282366920938463463374607431768211456
>>> 340282366920938463463374607431768211456**2
1157920892373161954235709850086879078532699846
65640564039457584007913129639936
>>> 115792089237316195423570985008687907853269
984665640564039457584007913129639936**2
1340780792994259709957402499820584612747936582
0592393377723561443721764030073546976801874298
1669034276900318581864860508537538828119465699
46433649006084096
89
ℝ 1.0
0.33333333
3.14159265
2.71828182
91
Basic operations
>>> 20.0 + 5.0 >>> 20.0 - 5.0
25.0 15.0
≈ 17 significant figures
93
Hidden imprecision
>>> 0.1
!
0.1
1.8446744073709552 e+19
1.8446744073709552 ×1019
95
1.8446744073709552×1019 18446744073709552000
- 18446744073709551616
384
96
>>> 3.402823669209385e+38**2
1.157920892373162e+77
1.2345678901234567 × 10N
17 significant figures
Positive values:
4.94065645841×10-324 < N < 8.98846567431×10307
98
Scientific notation
Scientific notation is a convenient way of expressing very large
or very small numbers.
General form:
𝑎𝑒𝑛 = 𝑎 × 10𝑛 , where 𝑎 is a float and 𝑛 is an integer.
Examples:
3𝑒8 = 3 × 108
9.109𝑒 − 19 = 9.109 × 10−19
99
Exercise: In the Interactive Python Terminal, try these
instructions and write what each instruction does. First example
already done
100
Variables
In programming languages generally, a variable name
represents a value of a given type (int, float, etc.) stored in a
fixed memory location. The value of a variable can be
changed but not the variable type. This is not the case in
Python where variables are typed dynamically as illustrated
below
103
Complex numbers ℂ
Imaginary axis
𝑧 = 𝑥 + 𝑖𝑦
𝑟 = 𝑟𝑒 𝑖𝜃
Python has all the functions to 𝜃
manipulate complex numbers.
In Python 𝑗 = −1 Real axis
𝑧 = 𝑅𝑒(𝑧) + 𝐼𝑚 𝑧 𝑗
104
cmath library
Calculations in ℂ
We now have all the functions to manipulate complex numbers.
ℂ Operations in Python
107
More operations in ℂ -1
The length of 𝑧 is the modulus given by
𝑧 = 𝑥2 + 𝑦2
In Python the one parameter, absolute function
written
abs(..)
gives the modulus of a complex number.
109
More operations in ℂ -2
The argument of 𝑧, written 𝑎𝑟𝑔 𝑧 is the angle
between 𝑧 𝑥, 𝑦 and the real axis where
𝑦
𝑎𝑟𝑔 𝑧 = 𝑎𝑟𝑐𝑡𝑎𝑛
𝑥
The one parameter function
phase(..)
gives the argument in radians. The principal value is
given, i.e. −𝜋 ≤ 𝑎𝑟𝑔 𝑧 ≤ 𝜋.
110
More operations in ℂ -3
Converting complex numbers from Cartesian 𝑥, 𝑦
to polar form 𝑟, 𝜃 is a fairly straightforward
mathematical exercise. How is this done in Python?
A single argument function
polar(..) 𝑟, 𝜃 ; 𝑟 = 𝑧 and 𝜃 = 𝑡𝑎𝑛−1 𝑦/𝑥
● polar(x+yj)
● polar(complex . . , . . )
111
Exercise
1. 223 ÷ 71
2. (1 + 1/10)10
3. (1 + 1/100)100
4. (1 + 1/1000)1000
112
6 + 10 16 int
int int
Check on type
115
Examples
116
bool True ✓
The Boolean type has precisely two values
bool False ✗
117
= == equals
“Syntactic sugar”
A common question in maths: 𝑥 ∈ 𝑎, 𝑏 ?
0 < number
number < 10
>>> number = 4
True
119
Boolean operations
bool
? bool
bool
Examples:
False
True
126
“Order of precedence”
Summary
Comparisons == != < > <= >=
Order of precedence
128
Exercise
Predict whether these expressions will evaluate to True or False.
Then try them.
3. 60 - 45 / 5 + 10 == 1
129
Exercise
Predict the outcome in the following numerical examples and then run
Expression:
(6 <= 6) and (5 < 3)
(6 <= 6) or (5 < 3)
(5 != 6)
“Syntactic sugar”
a+= b a = a + b
a-= b a = a - b
a*= b a = a * b
a /= b a = a / b
a **= b a = a ** b
a %= b a = a % b
131
Deleting a name
>>> print(value)
10 Known
variable
>>> del value
>>> print(thing)
Before
What is
Loop body run each
loop?
After
133
Before number = 1
✘ ✔ ✘ ✔
print(number)
Loop body number += 1
After print('Complete')
134
✘ ✔
print(number)
␣␣␣␣ print(number)
number += 1 number += 1
␣␣␣␣
print('Done!') print('Done!')
135
print('Done!')
136
␣␣␣␣print(number)
loop body
␣␣␣␣number += 1
Four spaces’ indentation
indicate a “block” of code.
print('Done!')
sum += number
␣␣␣␣ Processing in the loop
Lists
Lists are sequences of values, very similar to strings,
except that each element can be of any type – they are
heterogeneous. The syntax for creating a list is [……]
where each element is separated with a ,
['American','Asian','Bermudan','Binary‘,……]
[3.141592653589793,1.5707963267948966, 0.0]
What is a list?
Consider the first list on the previous slide (more
lengthier)
American, Asian, Bermudan, Binary, Cliquet, Lookback, Parisian,
Passport, …, Vanilla
A list of irrationals
145
0 1 2 3 4 5 6 7
-8 -7 -6 -5 -4 -3 -2 -1
getting at the last item
>>> primes[-1]
19
146
If pop() is called with no arguments, it removes the last element of the list.
In [4]: b = [0.1,0.2,0.3]
In [5]: b.pop()
Out[5]: 0.3 In [4]: del b[0]
In [6]: b In [5]: b
Out[6]: [0.1,0.2] Out[5]: [0.3]
149
0 len() function:
length of list
primes
Maximum
7
index is 7
151
Tuples
Tuples are like lists, except that they cannot be
modified once created, that is they are immutable. In
Python, lists, are easily created using the syntax (…,
…, …), or even …, …:
152
Unpacking tuples
Tuples can be unpacked by assigning it to a comma-
separated list of variables
Simpler Tuples
To construct a single-element tuple, put an extra comma:
Lists to Tuples
It is tedious to write:
In [1]: a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Exercise
Track what is happening to this list at each stage. Do this initially
by hand. After each line, work out what you think the numbers will be
and then check by printing out.
>>> numbers = [5, 7, 11, 13, 17, 19, 29, 31]
>>> numbers[1] = 3
>>> numbers[3] = 37
>>> print(primes)
[2, 3, 5, 7, 11, 13, 17, 19]
>>> primes.append(23)
The function doesn’t
return any value.
>>> primes.append(29)
>>> primes.append(31)
>>> numbers.reverse()
The function doesn’t
return any value.
>>> print(numbers)
[1, 5, 7, 4] It modifies
the list itself.
165
>>> numbers.sort()
The function does not
return the sorted list.
>>> print(numbers)
Numerical order.
166
>>> greek.sort()
>>> print(greek)
Alphabetical order
of the words.
167
>>> greek
0 1
Displaced
168
>>> print(numbers)
[7, 4, 7, 2, 5, 4]
>>> print(numbers)
[7, 4, 7, 2, 5, 4]
There are two instances of 4.
>>> numbers.remove(4)
>>> print(numbers)
[7, 7, 2, 5, 4]
>>> primes
Concatenation
Create a new list
Augmented assignment
Is an item in a list? ― 1
✗
x must be in the
list before it can
be removed
173
Is an item in a list? ― 2
>>> odds = [3, 5, 7, 9]
>>> 2 in odds
False
>>> 3 in odds
True
True
174
Precedence
First
x not in y x in y
range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Start at 0
range(3, 10) [3, 4, 5, 6, 7, 8, 9]
Indices of lists
>>> primes = [ 2, 3, 5, 7, 11, 13, 17, 19]
>>> len(primes)
>>> list(range(8))
0 1 2 3 4 5 6 7
>>> y = 3.14
>>> type(y)
<class 'float'>
>>> print(z)
(20, 3.14)
>>> print(w)
(20, 3.14)
179
Splitting up a tuple
>>> print(z)
(20, 3.14)
>>> print(a)
20
>>> print(b)
3.14
180
3.14
>>> z[0] = 10
numpy pyodbc
MySQLdb MySQL
cx_oracle Oracle
Finding modules
>>> help(math)
NAME
math
DESCRIPTION
This module is always available. It provides
access to the mathematical functions defined
by the C standard.
…
185
FUNCTIONS
acos(x)
Return the arc cosine (measured in
radians) of x.
…
>>> math.acos(1.0)
0.0
186
DATA
e = 2.718281828459045
pi = 3.141592653589793
…
>>> math.pi
3.141592653589793
186
187
Functions
𝑦 =f 𝑥
188
len(thing) float(thing)
print(line) iter(list)
type(thing) list(thing)
chr(number) str(thing)
Not that many! “The Python Way”:
If it is appropriate to an object,188
make it a method of that object.
189
… write
… test
… fix
… improve
… add to
“Structured
programming”
… develop
190
Defining a function
Approximating a Cumulative
Distribution Function (CDF)
A random variable X~𝑁 0,1 has CDF
𝑥
1 1
− 𝑠2
𝑁 𝑥 = 𝑃𝑟 𝑋 < 𝑥 = න 𝑒 2 𝑑𝑠
2𝜋 −∞
1.2
0.8
CDF(x)
0.6
0.4
0.2
0
-6 -4 -2 0 2 4 6
x
194
The Algorithm
We can approximate this improper integral by using the numerical
scheme which is accurate to 6 decimal places
𝑁 𝑥 =
1 − 𝑛 𝑥 𝑎1 𝑘 + 𝑎2 𝑘 2 + 𝑎3 𝑘 3 + 𝑎4 𝑘 4 + 𝑎5 𝑘 5 𝑥 ≥ 0
൝
1 − 𝑁 −𝑥 𝑥<0
Where
1
𝑘= and
1+0.2316419𝑥
𝑎1 =0.319381530, 𝑎2 =−0.356563782, 𝑎3 =1.781477937
𝑎4 =−1.821255978, 𝑎5 =1.330274429,
1 −1𝑥 2
𝑛 𝑥 = 𝑒 2
2𝜋
195
196
OPTION
PRICER
199
Numpy
The numpy package is used in almost all numerical
computation using Python. The package provides high-
performance vector, matrix and higher-dimensional data
structures for Python. Its flagship object is the powerful N –
dimensional array
>>> from numpy import*
You can also use one or more of:
>>> from numpy.linalg import*
>>> from numpy.fft import*
>>> from numpy.random import*
and others
200
Arrays
The most basic numpy data type.
Matrices are specialised 2-D arrays.
Types int, float, complex forms available
𝟏 𝟐 𝟓
Example: 𝒂 = , 𝒃=
𝟑 𝟒 𝟔
Vector displayed
in row form
201
𝒃𝟎
𝒃= , A vector component 𝒃𝒊 can be accessed in python as b[i]
𝒃𝟏
𝒂𝟎𝟎 𝒂𝟎𝟏
𝒂= , A component 𝒂𝒊𝒋 can be accessed in python as a[i,j]
𝒂𝟏𝟎 𝒂𝟏𝟏
205
plot([1,2,3,4],'b--')
208
Nonlinear Plot - Quadratic
209
Nonlinear Plot – Trig functions
210
Plotting a Gaussian
211
Complex Numbers
There should
be no space
We can combine
formats!
214
Rational Numbers
Algebraic Manipulations
A main use of CAS is to perform algebraic manipulations of expressions. For example, we
may wish to expand a product, factor an expression, or simplify an expression. The
functions for doing these basic operations in SymPy are demonstrated below:
Expand and factor
216
Simplify
The simplify function attempts to simplify an expression into a set of nicer looking smaller
terms using various techniques. More specific simplification alternatives to the simplify
functions also exist: trigsimp, powsimp, logcombine, etc
217
Calculus I – Differentiation I
A powerful feature of CAS is its Calculus functionality like derivatives and integrals of
algebraic expressions
Differentiation – Use the diff function. The first argument is the expression to take the
derivative of, and the second is the symbol by which to take the derivative:
New function defined
𝒅𝒏 𝒚
= 𝐝𝐢𝐟𝐟(y,x,n)
𝒅𝒙𝒏