0% found this document useful (0 votes)
103 views32 pages

Computational Programming With Python

This lecture introduces the Python programming language and computational programming using Python. It covers data types and variables in Python, importing modules, lists and operations on lists, for loops, and elementary plotting. Students are introduced to key Python concepts like importing NumPy, working in IPython, string manipulation, list comprehensions, and generating simple plots using Matplotlib.

Uploaded by

fragarat
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)
103 views32 pages

Computational Programming With Python

This lecture introduces the Python programming language and computational programming using Python. It covers data types and variables in Python, importing modules, lists and operations on lists, for loops, and elementary plotting. Students are introduced to key Python concepts like importing NumPy, working in IPython, string manipulation, list comprehensions, and generating simple plots using Matplotlib.

Uploaded by

fragarat
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/ 32

Computational Programming with Python

Lecture 1: First steps - A bit of everything

Center for Mathematical Sciences, Lund University


Lecturer: Claus Führer, Malin Christersson
This lecture
About this course
About Python
Data types and variables
Import modules
Lists
For loops
Elementary plo ng
Presenta on of teaching assistants
About Python

Why Python?
Python is...

Free and open source

It is a scrip ng language - an interpreted (not compiled) language

It has plenty of libraries among others the scien fic ones: linear algebra;
visualisa on tools; plo ng; image analysis; differen al equa ons solving; symbolic
computa ons; sta s cs; etc.

It has possible usages: Scien fic compu ng, scrip ng, web sites, text parsing, data
mining, ...
Premisses

We work with Python version ≥ 3.6.

We use an IPython shell

We use the work environment Spyder

We work (later) with the IPython notebook

We start our programs with

In [1]: from numpy import *


Course Book
Scien fic Compu ng with Python 3

Claus Führer, Jan Erik Solem, Olivier Verdier

December 2016
Examples
Python may be used in interac ve mode

(executed in an IPython shell)

In [2]: x = 3

In [3]: y = 5

In [4]: print(x + y)

Note:

In [2] is the prompt in IPython shell. It counts the statements. In the more basic
Python shell the prompt string is >>>
IPython
IPython is an enhanced Python interpreter.

Use the arrow keys to visit previous commands.

Use tab to auto-complete.

To get help on an object just type ? a er it and then return.


Examples: Linear Algebra
Let us solve

In [5]: from scipy.linalg import solve


M = array([[1., 2.],
[3., 4.]])
V = array([2., 1.])
x = solve(M, V)
print(x)

[-3. 2.5]
More examples
Compu ng and :

In [6]: print(exp(1j*pi)) # should return -1

(-1+1.2246467991473532e-16j)

In [7]: print(2**100)

1267650600228229401496703205376

Note: Everything following # is treated as a comment


Data types and variables

Numerical data types


A number is an integer ( int ), a real number ( float ) or a complex number ( complex ).

The usual opera ons are

+ and - addi on and subtrac on

* and / mul plica on and division

** power

In [8]: 2**(2+2)

Out[8]: 16

In [9]: 1j**2

Out[9]: (-1+0j)
Variables
A variable is a reference to an object. One uses the assignment operator = to assign a
value to a variable.

In [10]: my_int = 42
my_float = 3.14
my_complex = 5+1j
my_sum = my_float+my_complex
print(my_sum)
print(type(my_sum))

(8.14+1j)
<class 'complex'>

For complex numbers, j is a suffix to the imaginary part. The code 5+j will not work.
Strings
Strings are "lists" of characters enclosed by simple or double quotes.

str1 = '"Eureka" he shouted.'

str2 = "He had found what is now known as Archimedes' principle."


Multiple lines
You may also use triple quotes for strings including mul ple lines:

In [11]: str3 = """This is


a long,
long string."""
print(str3)

This is
a long,
long string.
Import modules

Importing Numpy
In order to use standard mathema cal functons in Python, you must import some module.
We will use numpy .

You can import numpy and then use dot-nota on a er the name numpy :

In [ ]: import numpy

print(numpy.exp(1j*numpy.pi))

You can import numpy and give it a shorter name:

In [ ]: import numpy as np

print(np.exp(1j*np.pi))
More about imports
You can choose what you want to import to avoid dot-nota on:

In [ ]: from numpy import exp, pi

print(exp(1j*pi))

You can make a star import to import everything from a module:

In [ ]: from numpy import *


Con guration of Spyder
Find the Preferences :

Tools - Preferences (Windows/Linux)

Python - Preferences (Mac)

Choose Editor and the tab Advanced settings , then click Edit template for
new modules . Here you can enter the code for imports that will be included in all new
files.

See instruc ons on Canvas for more informa on.


Lists
A Python list is an ordered list of objects, enclosed in square brackets.

One accesses elements of a list using zero-based indices inside square brackets.
List examples
In [12]: L1 = [1, 2]
print(L1[0])
print(L1[1])
# print(L1[2]) raises IndexError

1
2

In [13]: L2 = ['a', 1, [3, 4]]


print(L2[0])
print(L2[2])
print(L2[2][0])

a
[3, 4]
3
Negative indices
In [14]: L2 = ['a', 1, [3, 4]]
print(L2[-1]) # last element
print(L2[-1]) # second last element

[3, 4]
[3, 4]
List utilities ‐ range
range(n) can be used to fill a list with elements star ng with zero.

In [15]: L3 = list(range(5))
print(L3)

[0, 1, 2, 3, 4]
List utilities ‐ len
The func on `len(L) gives the the length of a list:

In [16]: L4 = ["Stockholm", "Paris", "Berlin"]


L5 = [[0,1], [10, 100, 1000, 10000]]
print(len(L4))
print(len(L5))
print(len(L5[-1]))

print(len(['a', 'b', 'c', 'd', 'e']))

3
2
4
5
List utilities ‐ append
Use the method append to append an element at the end of the list.

In [17]: L6 = ['a', 'b', 'c']


print(L6[-1])
L6.append('d')
print(L6[-1])

c
d
List comprehension
A convenient way to build up lists is to use the list comprehension construct, possibly with
a condi onal inside.

De nition

The syntax of a list comprehensipn is

[<expr> for <variable> in <list>]

Example:

In [18]: L1 = [2, 3, 10, 1, 5]


L2 = [x*2 for x in L1]
L3 = [x*2 for x in L1 if 4 < x <= 10]

print(L2)
print(L3)

[4, 6, 20, 2, 10]


[20, 10]
List comprehension in mathematics

Mathematical notation

This is very close to the mathema cal nota on for sets. Compare:

with

L2 = [2*x for x in L1]


Operations on lists
Adding two lists concatenates (sammanfogar) them:

In [19]: L1 = [1, 2]
L2 = [3, 4]
L3 = L1 + L2
print(L3)

[1, 2, 3, 4]
More operations on lists
Logically, mul plying a list with an integer concatenates the list with itself several mes:
n*L is equivalent to

In [20]: L = [1, 2]
print(3*L)

[1, 2, 1, 2, 1, 2]
for loops
A for loop allows to loop through a list using an index variable. This variable takes
succesively the values of the elements in the list.

Example:

In [21]: L = [1, 2, 10]


for s in L:
print(s * 2)

2
4
20
Repeating a task
One typical use of the for loop is to repeat a certain task a fixed number of mes:

In [ ]: n = 30
for i in range(n):
do_something # this gets executed n times
Indentation
The part to be repeated in the for loop has to be properly indented.

In [ ]: for elt in my_list:


do_something()
something_else()
etc
print("loop finished") # outside of the for loop

In contrast to other programming languages, the indenta on in Python is mandatory.


Elementary plotting
We must first make the central visualiza on tool in Python available:

In [22]: from matplotlib.pyplot import *

Then we generate two lists:

In [23]: x_list = list(range(100))


y_list = [sqrt(x) for x in x_list]
Then we make a graph:

In [24]: plot(x_list, y_list, 'o')


title('My first plot')
xlabel('x')
ylabel('Square root of x')
show() # not always needed

You might also like