0% found this document useful (0 votes)
17 views222 pages

Python Primer

Uploaded by

johan oldman
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views222 pages

Python Primer

Uploaded by

johan oldman
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 222

1

For Scientific Computing


2

Introduction
3

Who is this for?

This a two day workshop introducing Python as a scientific


computing language.

It is intended for those who are completely new to programming


in Python.

As well as an informal lecture style delivery we will also be doing


exercises.

This is based on popular Python based university courses at


Cambridge and UCL.
4

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.

• In the last several decades a third important and exciting


component has emerged, i.e. scientific computing.

• Scientific computing acts as an intersection of the former two


areas of science. It is often closely related to theory, but it also has
many characteristics in common with experimental work.

• It is therefore often viewed as a third branch of science.


6

The Need for Scientific Computing


• In most areas of science, computation is an invaluable
complement to both experiments and theory.

• Vast majority of both experimental and theoretical research


involve some numerical calculations, simulations or computer
modelling.

• In many studies, pure theory alone is insufficient in validating or


demonstrating results. On the other hand, experimentation as a
sole means of conducting an investigation may lack the scientific
rigour necessary to hold up to scrutiny.

• Experimental work may not be possible or may prove too costly.


7

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

The popularity of Python


10

Who uses Python?


Web applications and internet On-line games Finance

Finance

Science Instrument control


Embedded systems
11

Where does Python programing fit


into your life?
• Super small so shows up on embedded devices
• Several libraries for building great web apps
• Has a strong position in scientific computing. Heavily used in
science (CERN and NASA) with dedicated libraries to specific
areas
• NumPy and SciPy – general purposes
• EarthPy – earth sciences
• AstroPy – Astronomy
• Pygame – writing video games; supports art, music, sound,
video projects, mouse and keyboard interaction
• Python popular at Disney and Lucas Film
• Large community of users, easy to find help and documentation
12

Interpreted versus Compiled 1


Programs are indirectly executed by an interpreter program
which reads the source code and translates it while in motion,
into a series of computations and system calls. The source has to
be re-interpreted (and the interpreter present) each time the code
is executed.

• Slower than compiled, with limited access to the underlying


operating system and hardware
• Easier to program
• Less strict on coding errors
13

Interpreted versus Compiled 2


Most conventional kind of language is compiled. Programs are
converted into machine code by a compiler and then directly
executed. This executable file can be run without the need to
refer back to the source code.

• Give excellent performance with limited access to the


underlying operating system and hardware
• Can be difficult to program in
• Most of the software we use is delivered as compiled
binaries, from software which the use doesn’t see
14

Installation of Canopy Express


From the link
https://store.enthought.com/downloads
and download the version adapted to your system of Canopy
Express.

How to know if your PC/laptop is a 32 or 64-bit system


Linux uname -a and if you see x64 then 64-bit else 32-bit
Mac uname -a also
Windows Click Start, right-click My Computer, and then click
Properties if you see 64-bit it’s a 64-bit system
15

https://www.python.org/
16

https://docs.python.org/2/library/
17

Welcome to your new best friend!


https://docs.python.org/2/library/numeric.html
18

What sort of language is Python?

Compiled Interpreted
Explicitly Explicitly Implicitly
Purely
compiled compiled compiled
interpreted
to machine to byte to byte
code code code

C, C++, Java, C# Python Shell,


Fortran Perl
19

Distributions of Python
Python is a language, then there exist different distributions of
Python (Python official, Anaconda Python, Enthought Canopy,
pythonxy . . . ).

Each distribution provides specific tools (Editors, packages


pre-installed, support for a given platform . . . ).

On Linux and Mac OS, Pythons comes pre-installed with the


operating system. However, many useful packages (e.g. SciPy)
must be installed by hand. For its easy interface we will use
Enthought Canopy.
20

Python 2 or 3

 Two Python versions are in current use: Python 2 and


Python 3.

 Python 3 is not backward compatible with Python 2.

 The largest community is still using Python 2 since there is


still several packages incompatible with Python 3.

 That’s why we will use Python 2 (more precisely Python


2.7.6).
21

Installation on Windows
22

Getting started with Canopy


23

Editing Environment

Click
24

Ready to start programming!


25

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

When a Python program starts it only has access to a basic


functions and classes.
(“int”, “dict”, “len”, “sum”, “range”, ...)

“Modules” contain additional functionality.

Use “import” to tell Python to load a module.


>>> import math
>>> import nltk
28

Type Powershell in the start menu


29

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 version

Python prompt
31

Quitting Python

>>> exit()

>>> quit() Any one


of these

>>> Ctrl + D
32

Welcome to Python – first program


Python prompt

Python command

>>> print('Hello, world!')

Hello, world! Output

>>> Python prompt


33

>>> print 'Hello, world!'

Hello, world!

>>>

We note that the same outcome is obtained without the


use of parentheses.
Brackets are used for consistency with version 3
A string is a sequence of characters enclosed in single or
double quotes.
34

Python interactive shell

You can type things directly into a running Python


session
35

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

In [4]: print 2+2*3


8

In [5]: print "hello", name


hello Riaz
38

Interactive on PowerShell
39

Python commands
Python “function”

Round brackets
― “parentheses”
print('Hello, world!')

Function’s “argument”

print ≠ PRINT “Case sensitive”


40

Defining strings
Strings can be defined using
● single quotes ' …. '

● double quotes " …. "

So strings defined using single and double quotes are


identical
41

Python text
Quotation marks

'Hello, world!'

The body
of the text

The quotes are not


part of the text itself.
!
42

Quotes?

print Command/statement

'print' Text/string
43

Manipulating Strings
 strings defined using single and double quotes are identical

 if you want to use quotes in your string, switch between single


and double quotes, example:

print(“He said, ‘after you, Sir!'.")

 Anything following # is a comment

 to use n in strings, use nn

 We can add arbitrary quotes by escaping them:


print("She said. n"Hen's coming.n".")
 nis reserved ( nn for a newline, nt for a tabulation, n’ . . . )
44

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

More on this shortly


45

Operations on Strings
Two strings can be joined/added together (concatenated) using
the + operator:
In [1]: "Hello, " + "Riaz!"
Out[1]: 'Hello, Riaz!'

To find out the length of a string, use the function len():


In [2]: len(“supercalifragilisticexpialidocious”) # from Mary Poppins
Out [2]: 34

We can join several copies of a string with the operator *


In [3]: 3 * "AbC"
Out [3]: 'AbCAbCAbC'
46

Slicing

Slicing is used to extract a portion of the string. Here


is an example:
>>> string = 'Press return to exit‘
>>> print string[0:12]
Press return␣

string[12]
47

Immutability

A string is an immutable object. Its individual


characters cannot be modified with an assignment
statement and it has a fixed length. Any attempt to be
violate this property will result in TypeError
Consider the code below:
48

Text: a string of characters

>>> type('Hello, world!')

<class 'str'> A string of characters

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!' Only simple


concatenation
'Hello, world!'

>>> 'Hello,' + 'world!' No spaces added


automatically.
'Hello,world!'
50

Single & double quotes

>>> 'Hello, world!' Single quotes

'Hello, world!' Single quotes

>>> "Hello, world!" Double quotes

'Hello, world!' Single quotes


51

Python strings: input & output

'Hello, world!'
Single or double
"Hello, world!" quotes on input.

Create same
string object.

'Hello, world!' Single quotes on output.


52

Uses of single & double quotes

>>> print('He said "hello" to her.')

He said "hello" to her.

>>> print("He said 'hello' to her.")

He said 'hello' to her.


53

Why we need different quotes

>>> print('He said 'hello' to her.')

File "<stdin>", line 1



print('He said 'hello' to her.')
^
SyntaxError: invalid syntax
54

Adding arbitrary quotes

>>> print('He said \'hello\' to her.')

He said 'hello' to her.

\' ' Just an ordinary


character.

\" " “Escaping”


55

Putting line breaks in text


Hello,
world! What we want

>>> print('Hello, ↵ Try this


world')

>>> print('Hello, ↵


File "<stdin>", line 1
print('Hello,
^
SyntaxError: EOL while
scanning string literal “EOL”: End Of Line
56

Inserting “special” characters


>>> print('Hello,\nworld!')
Hello, Treated as
world! a new line.

\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."

By default, Python assumes that the whole instruction is contained in


a single line.
59

Special input method for long text


''' Shoot all the blue jays you
want, if you can hit 'em, but
remember it's a sin to kill a
mockingbird. That was the
only time I ever heard Atticus
it was a sin to do something,
and I asked Miss Maudie
about it. '''
Multiple
lines
Triple
quotes
60

Python’s “secondary” prompt


Python asking for more
of the same command.
61

It’s still just text!

>>> 'Hello,\nworld!'

'Hello\nworld'
Python uses \n to represent
line breaks in strings.

>>> '''Hello,
... world!'''

'Hello\nworld' Exactly the same!


62

Your choice of input quotes:


Four inputs:

'Hello,\nworld!' "Hello,\nworld!"

'''Hello, """Hello,
world!''' world!"""

Same result:

str, ↵ w o r l d !
13 H e l l o
63

Attaching names to values


“variables”

>>> message='Hello, world!'

>>> message

'Hello, world!'

>>> type(message)

<class 'str'>

message str, ␣ w o r l d !
13 H e l l o
63
64

Some more types

>>> type(G’day!')

<class 'str'> string of characters

>>> type(-62)

<class 'int'> integer

>>> type(pi)

<class 'float'> floating point number


65

Converting text to integers


>>> int('10')
2 1 0
str int 10
10

>>> 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

Reading text files


This is the simplest script that opens a file for reading, loads its
contents into a text variable and closes the file. In my example the file
called Humpty.txt has location C:\Users\Riaz\Desktop\Humpty.txt

Single quotes also work


73

The with statement


Closing a file is easily overlooked. For this and other reasons it is better
to use the with statement:
74

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:

The range of these long integers is only limited by the amount of


available memory in the computer. Operations on long integers
are slower than on normal integers.
76

Simple Arithmetic Calculations –


BIDMAS or BODMAS

4+8/2
✘ ✔
(4 + 8) / 2 4 + (8 / 2)

6 8
77

Manipulating in-built functions


78

Converting text to floats

>>> float('10.0') '10.0' is a string

10.0 10.0 is a floating


point number

>>> float('␣10.␣') Spaces are ignored


10.0
79

Converting between ints and floats

>>> float(10)

10.0

>>> int(10.9)

10 Truncates
fractional part

>>> int(-10.9)

-10
80

Converting into text

>>> str(10) integer string

'10'

>>> str(10.000) float string

'10.0'
81

Converting between types

int() anything integer

float() anything float

str() anything string

Functions named after the type they convert into.


82
Exercise 4.0

Write python programs to do the following:

1. Prompt the user with the text “How much?␣”.

2. Convert the user’s answer to a floating point number.

3. Print 2.5 plus that number.


83

Integer arithmetic
>>> 10+5 >>> 25␣-␣5
15 10
Spaces around the
operator don’t matter.

>>> 20␣*␣5 >>> 20␣/␣5


100 4

>>> 20␣/␣3
6
84

Type-casting
>>> 20.0/3
6.666666666666667

>>> float(20)/3 >>> 20/float(3)


6.666666666666667 6.666666666666667

>>> float(20/3)
6.0
85

Integer powers **
We wish to calculate 43

>>> 4␣**␣3 Spaces around the


operator don’t matter.
64

>>> 4*␣*3 Spaces in the


operator do!
SyntaxError: invalid syntax
86

Integer remainders
Use “%” to obtain integer remainders

>>> 4␣%␣2 >>> 5␣%␣2


0 1
In the example above “%” is modulo and can be used to determine if an
integer is even or odd. 𝑥 ∈ ℤ and 𝑥%2 = 0 then 𝑥 is even, else 𝑥 is odd.

>>> 20%6
3

>>> -5␣%␣2
1 Remainder is always non-negative
87

How big can a Python integer be?


>>> 2**2
4

>>> 4**2
16

>>> 16**2
256

>>> 256**2
65536

>>> 65536**2
4294967296
88

How big can a Python integer be?


>>> 4294967296**2
18446744073709551616

>>> 18446744073709551616**2
340282366920938463463374607431768211456

>>> 340282366920938463463374607431768211456**2
1157920892373161954235709850086879078532699846
65640564039457584007913129639936

>>> 115792089237316195423570985008687907853269
984665640564039457584007913129639936**2
1340780792994259709957402499820584612747936582
0592393377723561443721764030073546976801874298
1669034276900318581864860508537538828119465699
46433649006084096
89

How big can a Python integer be?


10443888814131525066917527107166243825799642490473837803842334832839
53907971557456848826811934997558340890106714439262837987573438185793
60726323608785136527794595697654370999834036159013438371831442807001
18559462263763188393977127456723346843445866174968079087058037040712
84048740118609114467977783598029006686938976881787785946905630190260
94059957945343282346930302669644305902501597239986771421554169383555
98852914863182379144344967340878118726394964751001890413490084170616
There is no limit!
75093668333850551032972088269550769983616369411933015213796825837188
09183365675122131849284636812555022599830041234478486259567449219461
70238065059132456108257318353800876086221028342701976982023131690176
78006675195485079921636419370285375124784014907159135459982790513399
61155179427110683113409058427288427979155484978295432353451706522326
Except for
90613949059876930021229633956877828789484406160074129456749198230505
71642377154816321380631045902916136926708342856440730447899971901781
machine
46576347322385026725305989979599609079946920177462481771844986745565
memory
92501783290704731194331655508075682218465717463732968849128195203174
57002440926616910874148385078411929804522981857338977648103126085903
00130241346718972667321649151113160292078173803343609024380470834040
3154190336
90

Floating point numbers

ℝ 1.0
0.33333333
3.14159265
2.71828182
91

Basic operations
>>> 20.0 + 5.0 >>> 20.0 - 5.0
25.0 15.0

>>> 20.0 * 5.0 >>> 20.0 / 5.0


100.0 4.0

>>> 20.0 ** 5.0 Equivalent to integer arithmetic


3200000.0
92

Floating point imprecision


>>> 1.0 / 3.0
0.3333333333333333

>>> 10.0 / 3.0


If you are relying on
3.3333333333333335 this last decimal place,
you are doing it wrong!

≈ 17 significant figures
93

Hidden imprecision
>>> 0.1
!
0.1

>>> 0.1 + 0.1


0.2

>>> 0.1 + 0.1 + 0.1


Really: if you are relying on
0.30000000000000004 this last decimal place,
you are doing it wrong!
94

How big can a Python float be? ― 1


>>> 65536.0**2 So far, so good.
4294967296.0

>>> 4294967296.0**2 Switch to


1.8446744073709552e+19 “scientific notation”

1.8446744073709552 e+19
1.8446744073709552 ×1019
95

Floats are not exact


>>> 4294967296.0**2 Floating point
1.8446744073709552e+19

>>> 4294967296**2 Integer


18446744073709551616

1.8446744073709552×1019 18446744073709552000

- 18446744073709551616

384
96

How big can a Python float be? ― 2


>>> 1.8446744073709552e+19**2
3.402823669209385e+38

>>> 3.402823669209385e+38**2
1.157920892373162e+77

>>> 1.157920892373162e+77**2 So far, so good.


1.3407807929942597e+154

>>> 1.3407807929942597e+154**2 Too big!


OverflowError: (34,
'Numerical result out of range')
97

Floating point limits

1.2345678901234567 × 10N

17 significant figures

-325 < N < 308

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

Exercise: Write this small program in a script and write in


comment what will be the type and the value of the variables
𝑥1 ; 𝑥2 ; 𝑥3 and 𝑥4 after executing this code:

Validate your results using the instruction type(variable)


101

More notes on integers


In [1]:int(3.4)
Out[1]:3
In [2]:int(3.9)
Out[2]:3
In [3]:int(round(3.4))
Out[3]:3
In [4]:int(round(3.9))
Out[4]:4
102

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

This now makes use of all functions related to


complex numbers. Gives the correct value of −2𝑖
105

Calculations in ℂ
We now have all the functions to manipulate complex numbers.

Now try the following


106

ℂ Operations in Python
107

Other ways of handling ℂ


Complex number 𝑧 = 𝑥 + 𝑖𝑦 can also be expressed
as a two-tuple 𝑧 = 𝑥, 𝑦 using complex(x,y)
𝑧1 = 2 + 3𝑖 is written as complex(2,3)
𝑧2 = 𝑖 is written as complex(0,1)
𝑧3 = 1 is written as complex(1,0)
108

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

Evaluate and print out the following calculations:

1. 223 ÷ 71

2. (1 + 1/10)10

3. (1 + 1/100)100

4. (1 + 1/1000)1000
112

Comparisons – Truth and Falsehood


>>> 6 < 10 Asking the question
True

>>> 6 > 10 Asking the question
False

>>> 5 == 10 >>> 6 <> 10
False True
5 equal to 10?
6 is not equal to 10?
113

True & False


>>> type(True)
<type 'bool'> “Booleans”

6 + 10 16 int

int int

6 < 10 True bool


114

Check on type
115

Examples
116

True & False

bool True ✓
The Boolean type has precisely two values
bool False ✗
117

Six comparison operators


Maths Python Meaning

= == equals

≠ != <> not equal to

< < less than

> > greater than

≤ <= less than or equal

≥ >= greater than or equal


118

“Syntactic sugar”
A common question in maths: 𝑥 ∈ 𝑎, 𝑏 ?
0 < number

0 < number < 10 and

number < 10

>>> number = 4

>>> 0 < number < 10

True
119

Boolean operations
bool
? bool
bool

Numbers have arithmetic operations +, –, * … bool ✓

What operations do Booleans have? bool ✗


120

Boolean operations ― “and”


bool
and bool
bool

True and True True Both have to be True

True and False False

False and True False and is a strong


condition
False and False False
121

Boolean operations ― “and”

Examples:

>>> 5 < 10 and 6 < 8 5 < 10 True


and True
True 6 < 8 True

>>> 5 < 10 and 6 > 8 5 < 10 True


and False
False 6 > 8 False
122

Boolean operations ― “or”


bool
or bool
bool

True or True True At least


one has
True or False True to be True
Weaker
False or True True
condition than
and
False or False False
123

Boolean operations ― “or”

>>> 5 < 10 or 6 < 8 5 < 10 True


or True
True 6 < 8 True

>>> 5 < 10 or 6 > 8 5 < 10 True


or True
True 6 > 8 False
124

Boolean operations ― “not”

bool not bool

not True False

not False True


125

Boolean operations ― “not”

>>> not 6 < 7 6 < 7 True not False

False

>>> not 6 > 7 6 > 7 False not True

True
126

“Order of precedence”

The precedence of logical operators is even lower than that of


comparison operators.

First x**y -x +x x%y x/y x*y x-y x+y

x==y x!=y x>=y x>y x<=y x<y

not x x and y x or y Last


127

Summary
Comparisons == != < > <= >=

Numerical comparison 5 < 7

Alphabetical ordering 'dig' < 'dug'

Booleans True False

Boolean operators and or not

Order of precedence
128

Exercise
Predict whether these expressions will evaluate to True or False.
Then try them.

1. 'sparrow' > 'eagle'

2. 'dog' < 'Cat' or 45 % 3 == 15

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)

(5 < 3) and (6 <= 6) or (5 != 6)

(5 < 3) and ((6 <= 6) or (5 != 6))

not((5 < 3) and ((6 <= 6) or (5 != 6)))


130

“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)

Traceback (most recent call last):


File "<stdin>", line 1, in <module>
NameError: name 'thing' is not defined
Unknown
variable
132

Loops – The mechanics

Before

Loop test/condition Should the


loop run
✘ ✔ (again)?

What is
Loop body run each
loop?

After
133

Loop example: Count from 1 to 10

Before number = 1

Loop test number <= 10

✘ ✔ ✘ ✔

print(number)
Loop body number += 1

After print('Complete')
134

Loop example: Count from 1 to 10


number = 1 number = 1
keyword

while number <= 10 : number <= 10

✘ ✔

print(number)
␣␣␣␣ print(number)
number += 1 number += 1
␣␣␣␣

print('Done!') print('Done!')
135

Loop test: Count from 1 to 10


number = 1
“while” keyword
loop test
while number <= 10 : colon

print(number) A loop becomes an infinite loop if


␣␣␣␣ a condition never becomes
number += 1
␣␣␣␣ FALSE. Use caution with while
loops.

print('Done!')
136

Loop body: Count from 1 to 10


number = 1

while number <= 10 :

␣␣␣␣print(number)
loop body
␣␣␣␣number += 1
Four spaces’ indentation
indicate a “block” of code.
print('Done!')

The first unindented line


marks the end of the block.
137

Loop example: Code and output


138

For Loop for summing: code and output


139

Keep looping while … ?


uncertainty > tolerance

while uncertainty > tolerance :


␣␣␣␣
Do stuff.
␣␣␣␣
␣␣␣␣
␣␣␣␣
140

The “for loop” for adding

numbers = [45, 76, -23, 90, 15]

sum = 0 Set up before the loop

for number in numbers :

sum += number
␣␣␣␣ Processing in the loop

print(sum) Results after the loop


141

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]

[ 2, 3, 5, 7, 11, 13, 17, 19 ]

Programs usually don’t operate on single values, but on


whole collections of them.
142

What is a list?
Consider the first list on the previous slide (more
lengthier)
American, Asian, Bermudan, Binary, Cliquet, Lookback, Parisian,
Passport, …, Vanilla

A sequence of values The names of option’s contracts

Values stored in order Alphabetic

Individual value identified “Binary” is the name of the


by position in the sequence element number 3 in the list
143

Creating a list in Python

A sequence of values The prime numbers


less than sixty

Values stored in order Numerical order

Individual value identified 17 is the element number six


by position in the sequence
144

A list of irrationals
145

Counting from the end – indexing from


the back
>>> primes = [ 2, 3, 5, 7, 11, 13, 17, 19]

0 1 2 3 4 5 6 7

[2, 3, 5, 7, 11, 13, 17, 19]

-8 -7 -6 -5 -4 -3 -2 -1
getting at the last item
>>> primes[-1]
19
146

Elements in a list can differ in <type>


4 elements of type int, float,
character, float in turn

First element in list changed to


a string
147

Inserting element using list methods


List methods are an alternative, more readable way of inserting elements.
append()adds an element to the end of a list:
In [1]: b = [0.1, 0.2]
In [2]: b.append(0.9)
In [3]: b
Out[3]: [0.1, 0.2, 0.9]

extend() appends all elements of another list:


In [4]: b.extend([7, 8])
In [5]: b
Out[5]: [0.1, 0.2, 0.9, 7, 8]

insert(i, x) inserts x before ith element:


In [6]: b.insert(1, 5)
In [7]: b
Out[7]: [0.1, 5, 0.2, 0.9, 7, 8]
148

Further insertion using list methods


List methods are an alternative, more readable way of inserting elements.
pop(i) removes and returns the 𝑖 𝑡ℎ element:
In [1]: b = [0.1,0.2,0.3]
In [2]: b.pop(1) # removes 0.2 from list and returns value
Out [2]: 0.2
In[3]: b
Out[3]:[0.1, 0.3]

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

Deletion from a list


The del() statement can be used to remove an element.
Using b = [0.1,0.2,0.3]
from the previous slide :
In [7]: del b[1]
In [8]: b
Out[8]: [0.1, 0.3]
150

Length of a list – use len


list
>>> len(primes)
8 8

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

Trying to assign a new value to an element in a


tuple results in an error.
153

Simpler Tuples
To construct a single-element tuple, put an extra comma:

An empty tuple is denoted by ()


154

Lists to Tuples

To convert a list to a tuple, use the function tuple():


In [3]: stuff = [7, ’xyz’]
In [4]: tuple(stuff)
Out[4]: (7, ’xyz’)
In [5]: stuffs=tuple(stuff)
In [5]: print stuffs
Out [5]: (7, ’xyz’)
155

Indexing and slicing


Indexing and slicing works as for lists:
In [1]: address = ’UK’, ’London’, ’WC1E
6BT’
In [2]: address[1]
Out[2]: ’London’
In [3]: address[1][0:3]
Out[3]: ’Lon’
However assignment is not allowed. So e.g. the following is
not allowed:
In [4]: address[2] = ‘NW1 1AB’
156
Loops again!
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:
The range() function 157

It is tedious to write:
In [1]: a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

This is shorter and equivalent:


In [2]: a = range(10)
range(n) returns the list of integers from 0 up to but not including n.
range(m, n) returns the list of integers from m up to but not
including n:
In [3]: range(5, 10)
Out[3]: [5, 6, 7, 8, 9]
range(m, n, s) returns the list containing every 𝑠 𝑡ℎ integer from m up
to but not including n:
In [4]: range(4, 10, 2)
Out[4]: [4, 6, 8]
158

Iteration over integers I


A common use case of range() is iteration over lists of integers.

range([start,] stop[, step]) -> list of integers


print range(1,10,2) prints out [1, 3, 5, 7, 9]
159

Iteration over integers II

Note range(5) does not include 5


160
Iteration over integers III

Again note range(3) does not include 3


161
Iteration over integers IV
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:
162

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

>>> del numbers[3]

>>> numbers[3] = 37

>>> numbers[4] = numbers[5]

>>> numbers = [5, 7, 11, 13, 17, 19, 29, 31]


163

Using the append() method

>>> 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)

>>> primes.append(37) It modifies


the list itself.
>>> print(primes)
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]
164

Other methods on lists: reverse()

>>> numbers = [4, 7, 5, 1]

>>> numbers.reverse()
The function doesn’t
return any value.
>>> print(numbers)

[1, 5, 7, 4] It modifies
the list itself.
165

Other methods on lists: sort()

>>> numbers = [4, 7, 5, 1]

>>> numbers.sort()
The function does not
return the sorted list.
>>> print(numbers)

[1, 4, 5, 7] It sorts the


list itself.

Numerical order.
166

Other methods on lists: sort()

>>> greek = ['alpha', 'delta', 'beta', 'gamma']

>>> greek.sort()

>>> print(greek)

['alpha', 'beta', 'delta', 'gamma']

Alphabetical order
of the words.
167

Other methods on lists: insert()


0 1 2

>>> greek = ['alpha', 'gamma', 'delta']

>>> greek.insert(1, 'beta' )

Where to insert What to insert

>>> greek

['alpha', 'beta', 'gamma', 'delta']

0 1
Displaced
168

Other methods on lists: remove()

>>> numbers = [7, 4, 8, 7, 2, 5, 4]

>>> numbers.remove(8) Value to remove

>>> print(numbers)

[7, 4, 7, 2, 5, 4]

c.f. del numbers[2] Index to remove


169

Other methods on lists: remove()

>>> print(numbers)

[7, 4, 7, 2, 5, 4]
There are two instances of 4.
>>> numbers.remove(4)

>>> print(numbers)

[7, 7, 2, 5, 4]

Only the first instance is removed


170

Adding to a list : “+”

>>> primes

[2, 3, 5, 7, 11, 13, 17, 19]

Concatenation List to add


operator

>>> primes + [23, 29, 31]

[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]


171

Concatenation
Create a new list

>>> newlist = primes + [23, 29, 31]

Update the list

>>> primes = primes + [23, 29, 31]

Augmented assignment

>>> primes += [23, 29, 31]


172

Is an item in a list? ― 1

>>> odds = [3, 5, 7, 9] Does not include 2

>>> odds.remove(2) Try to remove 2

Traceback (most recent call last): Hard error


File "<stdin>", line 1, in <module>
ValueError: list.remove(x): x not in list


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

>>> 2 not in odds

True
174

Precedence
First

x**y -x +x x%y x/y x*y x-y x+y

x==y x!=y x>=y x>y x<=y x<y

x not in y x in y

not x x and y x or y The list now contains


every operator we
Last meet in this course.
175

Ranges of numbers again


via list()

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]

range(3, 10, 2) [3, 5, 7, 9] Every nth number

range(10, 3, -2) [10, 8, 6, 4] Negative steps


176

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] valid indices

0 1 2 3 4 5 6 7

[2, 3, 5, 7, 11, 13, 17, 19]


177

Tuples as single objects ― 1


>>> x = 20
>>> type(x)
<class 'int'>

>>> y = 3.14
>>> type(y)
<class 'float'>

>>> z = (20, 3.14) One name → Pair of values


>>> type(z)
<class 'tuple'> A single object
178

Tuples as single objects ― 2

>>> z = (20, 3.14)

>>> print(z)

(20, 3.14)

>>> w = z Single name → Single tuple

>>> print(w)

(20, 3.14)
179

Splitting up a tuple

>>> print(z)

(20, 3.14)

>>> (a,b) = z Two names → Single tuple

>>> print(a)

20

>>> print(b)

3.14
180

How tuples are like lists

>>> z = (20, 3.14)

>>> z[1] Indices

3.14

>>> len(z) Length

>>> z + (10, 2.17) Concatenation

(20, 3.14, 10, 2.17)


181

How tuples are not like lists

>>> z = (20, 3.14)

>>> z[0] = 10

Traceback (most recent call last):


File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not
support item assignment “Immutable”
182

Additional downloadable modules


Numerical Databases

numpy pyodbc

scipy psycopg2 PostgreSQL

MySQLdb MySQL

cx_oracle Oracle

Graphics ibm_db DB2

matplotlib pymssql SQL Server


183

Finding modules

Python: Built-in modules

SciPy: Scientific Python modules

PyPI: Python Package Index

Search: “Python3 module for X”


184

Help with modules

>>> import math

>>> help(math)

NAME
math

DESCRIPTION
This module is always available. It provides
access to the mathematical functions defined
by the C standard.


185

Help with module functions


FUNCTIONS

acos(x)
Return the arc cosine (measured in
radians) of x.

>>> math.acos(1.0)

0.0
186

Help with module constants


DATA
e = 2.718281828459045
pi = 3.141592653589793

>>> math.pi

3.141592653589793

186
187

Functions

𝑦 =f 𝑥
188

Functions we have met and will meet


input(prompt) bool(thing)

len(thing) float(thing)

open(filename, mode) int(thing)

print(line) iter(list)

type(thing) list(thing)

ord(char) range(from, to, stride)

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

Why write our own functions?


Easier to …
… read

… write

… test

… fix

… improve

… add to
“Structured
programming”
… develop
190

Defining a function

(y1, y2, y3) = f(x1, x2, x3, x4, x5)

Identify the inputs

Identify the processing

Identify the outputs


191

User defined functions


We now write our own functions. 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.
192

Writing a maths function


193

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

Input from keyboard - revised


The function raw_input() can be used to request
information from the user via the keyboard.
Example: inputting text
197

More keyboard input - numerical


The function input() can be used to request
information from the user via the keyboard.
Example: inputting numerical values
198

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

Simple operations on arrays


𝟏 𝟐 𝟓 𝟑
𝒂= , 𝒃= ,𝒄=
𝟑 𝟒 𝟔 𝟐
𝟏𝟕
Example: 𝒅 = 𝒂 × 𝒃 = ; 𝒅 ∙ 𝒄 = 𝟏𝟕, 𝟑𝟗 ∙ 𝟑, 𝟐 =129
𝟑𝟗
202
Filling arrays with identical elements
203
Filling arrays with random numbers

rand: random numbers uniformly distributed between 0 and 1

nrand: Normal (Gaussian) distribution 𝑁 0,1

Other standard distributions are also available


204
Indexing starts at zero!

𝒃𝟎
𝒃= , A vector component 𝒃𝒊 can be accessed in python as b[i]
𝒃𝟏
𝒂𝟎𝟎 𝒂𝟎𝟏
𝒂= , A component 𝒂𝒊𝒋 can be accessed in python as a[i,j]
𝒂𝟏𝟎 𝒂𝟏𝟏
205

matplotlib – 2D and 3D plotting


matplotlib.pyplot is an amazing 2D and 3D graphics
library containing a collection of command line style
functions that make matplotlib work like MATLAB.
The advantages of using this library include:
● As with Python, easy to get started
● Support for formatted labels and texts
● Superior levels of control of all aspects of high
quality figures in many formats (e.g. PNG, PDF,
SVG, EPS, PGF)
206

matplotlib – getting started


To get started, the easy way to include matplotlib in a
Python program is with:

Can also have

The advantage of using matplotlib is being able to


draw MATLAB still graphs.
207
First Plot
plot([1,2,3,4],'r')

Line colour can be


controlled

Line style can be


changed

plot([1,2,3,4],'b--')
208
Nonlinear Plot - Quadratic
209
Nonlinear Plot – Trig functions
210
Plotting a Gaussian
211

Sympy – Symbolic algebra in Python


Sympy is one of two Computer Algebra Systems (CAS) for Python. To
get started, import the module sympy:

To get beautiful formatted output, simply run:

Symbolic Variables: In SymPy we need to create symbols for the


variables we want to work with. This can be done using the Symbol
class.
212

Use of Symbolic Variables

We can add assumptions to variables when we create them:


213

Complex Numbers

The imaginary unit 𝑖 = −1 denoted I in SymPy:

There should
be no space

We can combine
formats!
214
Rational Numbers

There are three different numerical


types in SymPy: Real,
Rational, Integer:
215

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

Differentiate 𝑦 wrt 𝑥 once

Differentiate 𝑦 wrt 𝑥 twice

Differentiate 𝑦 wrt 𝑥 three


times
218
Calculus I – Differentiation II
Trig functions and transcendental functions can also be differentiated

New function defined


Differentiate 𝑦 wrt 𝑥 once

Differentiate 𝑦 twice wrt 𝑥

New function defined

𝒅𝒏 𝒚
= 𝐝𝐢𝐟𝐟(y,x,n)
𝒅𝒙𝒏

where n is the order of


differentiation
219
Calculus I – Differentiation III
We can do partial differentiation on multivariate functions
220
Calculus II – Integration I
Integration is done in a similar fashion using the function integrate()

Note that oo is the SymPy


notation for infinity
221
Exercises
1. Write a program that returns the Celsius 𝐶 value for a given temperature measured
in Fahrenheit 𝐹. The relation between these two is given by 5 𝐹 − 32 = 9𝐶. As an
example, the input 50 returns 10.
2. The time period 𝑇 for a simple pendulum can be determined from
𝑙
𝑇 = 2𝜋 , where 𝑙 is the length of string and 𝑔 = 9.81𝑚𝑠 −2 is the constant
𝑔
acceleration due to gravity. Write a program to determine 𝑇 for varying lengths of
string.
3. Calculate the PV of £5400 in three years time given the constant risk-free interest
rate is 3.4%.
4. How much is £25000 worth in five years time if the constant risk-free interest rate
is 4.4% with continuous compounding.
5. Experiment with different mathematical functions from the math module by
writing various mathematical scripts.
6. Write programs to check the following formulae by inputting 𝑛 (your choice) and
then computing and comparing both sides of the equation
𝑛 𝑛+1 𝑛 𝑛+1 2𝑛+1 𝑛2 𝑛+1 2
a. σ𝑛𝑖=1 𝑖 = b. σ𝑛𝑖=1 𝑖 2 = b. σ𝑛𝑖=1 𝑖 3 =
2 6 4
222

More exercises to follow!


There will be a further course in
September!

You might also like