PH-113 Python Primer

Table of Contents

Welcome

Welcome to PH-113 Python Primer

Motivation

  • Computers are everywhere
  • Not just a glorified typewritter
    • Automate: off-load repetitive tasks
    • Do tasks that would otherwise be impractical
    • Becomes an extension of your brain!
  • If entering workforce in 2020s, need to know how to program a computer

Python

  • A language with which to tell computer what to do
  • Other languages are available
    • most concepts are common
    • some design choices are very different
  • Much closer the human-level mathematics than to computer-level 1s and 0s

Spyder and IPython

Spyder is an Interactive Development Environment, IDE for short.

  • Text-editor (with syntax highlighting etc)
  • Code interpreter (for running and testing the code)
  • Other useful bits and bobs

IPython is an interactive Python shell

  • Can have a live two-way dialog with the computer
  • Give instructions
  • Make mathematical definitions
    • and then ask it things!
  • Try stuff, and see what happens

Useful features include:

  • Up arrow brings up the last command so we can tweak and try again
  • Pressing [TAB] gives suggested completions for a partially written instruction
  • Appending a question mark ? gives help for that instruction

Format for today

  • Introduction as relevant to physicists
    • How to phrase mathematical ideas
    • not e.g. how to make a good user-interface
  • Contents
    • Basics
    • Common errors
    • Summation and series
    • Plotting
    • Functions
  • Code examples
    • Please type these in
      • i.e. not copy-and-paste
      • much like taking notes in a lecture
      • try variations; experiment!
  • Some challenge questions
  • Website will be available after Skills Sessions

Stuff in this kind of box is code which you can type in

def f(x):
    return x*x
f(2)

Stuff in this kind of box is the output that the code might produce

4

How to start Spyder

  • Swansea Uni Unified Desktop
  • Specialist Apps
    • College of Science
      • Physics
  • Anaconda Command Prompt
    • Type "spyder" and hit enter

1.png

Figure 1: Swansea UDE, Specialists Apps, CoS, Physics, Anaconda

2.png

Figure 2: Anaconda Command Prompt

3.png

Figure 3: Type "spyder"

4.png

Figure 4: Should look like this.

Introduction

Start with the basics

Type the following into the Python interpreter.

2+2
4

Does what we'd expect. A glorified calculator. Also multiplication

3*6
18

And raising numbers to a power

3**4
81

Can also do real numbers

3.6*52.3
188.28

Non-integer powers

96**0.4
6.207382295661439

and even complex numbers

3+4j
(3+4j)

(\(j=\sqrt{-1}\) rather than \(i\) because engineers prefer this convention) We can also handle text, but we won't dwell on that today

"Steve"
Steve

Variables

The computer has a memory, and we can store values in a variable

n = 2
x = 3.6
z = 3 + 4j
x*n
7.2

And we can store the result of a calculations in another variable

y=x*n

and y stores the value we expect

y
7.2

Python3 does what you expect when dividing two integers

3/2
1.5

(If this comes out as 1 rather than 1.5, then you're probably using Python2 rather than Python3)

Lists

Often, we want to store many values in one object. In Python, the most common such container is a list.

Create a list manually by writing lots of Python objects enclosed by square brackets and separated by commas:

[1,2,3,"cat",9,9]
[1, 2, 3, 'cat', 9, 9]

Note that you can put any Python object in a list, including a list…

There are ways to create lists and compute things using lists. We'll see an example shortly.

Functions

A mathematical function, such as \(f(x)=x^2\), takes a value and returns something. e.g. \(f(2)\) takes the value \(3\) and returns \(3^2=9\).

There are some useful built-in functions. For example, abs, when given a complex number, returns \(\lVert z\rVert\):

z = 3+4j
abs(z)
5.0

(For \(z=3+4j\), \(\lVert z\rVert = \sqrt{3^2 + 4^2} = \sqrt{25} = 5\).) We will also meet sum, range, and a few others…

We will write our own functions soon.

In general, function can

  • accept anything as input
  • do anything to it
  • return anything as output

Build up complex behaviour with simple, well-tested functions.

Common errors

Python typically gives a sensible error message

Syntax Errors

 2 n
  2 n
    ^
SyntaxError: invalid syntax

You must put * between two things if you want to multiply them, which is different from mathematics where you might write \(2n\) to mean \(2\times n\).

Divide by zero

n/0
----> 1 n/0
ZeroDivisionError: integer division or modulo by zero

Type Error and …

We might write n(10) expecting this to mean \(n\times 10\), but to Python it looks like we're trying to use n as though it were a function; it's not a function, it's an integer.

n(10)
----> 1 n(10)
TypeError: 'int' object is not callable

Notice how this complaint is phrased: Python doesn't care that n isn't a function; rather, it cares that it can't "call" n. Calling is the name for passing something to a function.

… Duck Typing

Python doesn't care what something is. It cares what it can do. Or rather, it cares what properties something has. This is called Duck Typing.

If it looks like a duck, swims like a duck, and quacks like a duck, then it probably is a duck.

For example, what's the 3rd element of this list (noting that we start counting at 0)

stuff = [0,1,2,3,4]
stuff[3]
3

What if stuff were a string? It still makes sense to ask what's the 3rd element in a string:

stuff = "abcdefg"
stuff[3]
d

Python doesn't care what stuff is, it just cares that it is sensible to ask what the 3rd element is. This is very powerful, but very (very!) different from most other languages. It is not the only way to program. (See, e.g. Haskell, or a more traditional language such as C.)

Task 1: Calculation

Log in to Blackboard; password anaconda. Answer the following question. Use variables to assign the values to e and pi.

i.e. Do not type the numbers out by hand more than once. Store them and reuse them.

´╗┐Set \(e=2.71828\) and \(\pi = 3.14159\), and compute \(e^{-\pi/2} + e^{i\pi}\), where \(i^2=-1\). Enter the real part into Blackboard.

Summation and series

The power of a computer comes from doing repetitivite things.

Summing 1 to 10

Suppose we want to find the sum of all the natural numbers from \(1\) to \(10\). We can make a list of these numbers and add them all up:

listOfNumbers = [1,2,3,4,5,6,7,8,9,10]
sum(listOfNumbers)
55

where we've used listOfNumbers as the name for this thing, because that reminds us what it is, and we don't have to stick to single letters, like \(x\) and \(y\), as is the convention in mathematics.

Summing 1 to 10000

Suppose we want to find the sum up to 10000. We can't type these all out by hand. The built-in function range does this for us. i.e., instead of

listOfNumbers = [1,2,3,4,5,6,7,8,9,10]
sum(listOfNumbers)
55

try

sum(range(10))
45

Beware that range(N) goes from 0 to N-1. We can use range slightly differently to get the numbers we want:

sum(range(1,11))
55

Summing \(1\) to \(10000\) is then easy:

sum(range(1,10001))
50005000

But that's a very boring series… \(\sum_{n=1}^Nn\)… what about something more useful?

\(\pi\)

With one more ingredient, we can explore all sorts of series. For example, the Leibniz formula for \(\pi\) is \[\pi=4\sum_{n=0}^\infty\frac{(-1)^n}{2n+1}\] i.e. we can build \(\pi\) just using integers. The first thing we need to do is convert each integer n into a term in this series

(-1)**n/(2*n+1)

Python has a particularly compact way of writing this for a list of numbers (called List Comprehension)

[(-1)**n/(2*n+1) for n in range(10)]
[1.00,-0.33,0.20,-0.14,0.11,-0.09,0.08,-0.07,0.06,-0.05]

We can do something to each value from range. Next, we just have to sum these and multiply by 4 to get an approximation for \(\pi\):

4*sum([(-1)**n/(2*n+1) for n in range(100000)])
3.1415826535897198

We can't sum to \(\infty\), but we can go to 100000, and that's pretty close.

Task 2: Summation

Log in to Blackboard; password anaconda. You will be asked to answer one of the questions below.

Question 1

\[\sum_{k=1}^\infty \frac{k^3}{2^k}\]

Question 2

\[8\sum_{n=0}^\infty \frac{1}{(2n+1)^2}\]

Question 3

\[\sum_{n=1}^\infty \frac{1}{n^2}\]

Question 4

\[\sum_{n=0}^\infty\frac{1}{2^n}\]

Flow control

A mathematical function, such as \(f(x)=x^2\), takes a value and returns something. e.g. \(f(2)\) takes the value \(3\) and returns \(3^2=9\).

Here's some Python code defining \(f(x)=x^2\):

def f(x):
    return x*x

The word def is a keyword which Python understands to mean this is a function. The word return is a keyword meaning this is what the function returns.

The indentation of return is essential. It tells Python that this indented code belongs to the structure started with the word def.

Indentation is how Python structures code. Indentation can be nested.

Here's a for loop. This allows a block of code to be run several times, with one variable changed: (This example simply displays the square of each number from \(0\) to \(9\), inclusive.)

for n in range(10):
    print(n**2)

Let's say we want to display (print) only those numbers whose square is less than \(30\). We use an if statement to ask a question \(n^2 < 30\) and do something if that condition is true:

if n**2 < 30:
    print(n)

We want to do this for all the numbers between \(0\) and \(9\), so we put this if statement inside a for loop by indenting:

for n in range(10):
    if n**2 < 30:
        print(n)

Any of the above can be inside a function i.e. preceeded by a def and indented by one more level.

Task 3: Fill in the blanks

Nested for loops

If we want to test lots of combinations, we end up using for loops inside for loops, with indentation signalling which for loop goes inside which for loop.

The test, which we do for every combination, is encoded in an if statement.

This code is intended to test every combination of \(a,b,c\) up to \(100\) and see whether it is a Pythagorean triangle. Fill in the blanks.

for a in range(100):
    ___ b in range(100):
        for c __ _____(100):
            __ a**2 + b**2 == c**2:
                print(a,b,c)

Recursive function

A function which calls itself is called recursive. We encounter this in mathematics, too.

For example, the factorial of \(N\) is defined as \(N\) times the factorial of \(N-1\), with the special case that the factorial of \(0\) is equal to \(1\).

Step through the following function and fill in the blanks.

def factorial(n):
    if n == 0:
        ______ 1
    else:
        return n*_________(___)

Importing numpy

The core functionality of Python can be extended using modules, which we can import

The most common is numpy which we import like so

import numpy

We can then refer to functions and constants provided by numpy like so:

numpy.pi
3.141592653589793

Since "numpy" is a bit long, usually this is imported like so:

import numpy as np
np.pi
3.141592653589793

numpy provides array, which is like list except it supports mathematical operations:

a = np.array([1,2,3])
a**2
[1 4 9]

Using just a Python list, we would have to do something like

a = [1,2,3]
[n**2 for n in a]
[1, 4, 9]

Not only is the numpy way faster, it makes code more readable.

Arrays can be built from range and similar, or we can use numpy functions.

x = np.linspace(0,1,1001)

which gives \(1001\) values linearly spaced between \(0\) and \(1\) inclusive.

To calculate \(y=x^2\) for all \(1001\) values, we simply do

y = x**2

Objects

An object is a way of organising data, things about that data (properties), and things you can do with that data (methods).

A method is a function attached to a particular object.

For example, a numpy array has a shape property:

A = np.array([1,2,3])
A.shape
(3,)

In this case, the array is 1 dimensional and is of length 3. We can make 2D arrays (like a spreadsheet or a matrix), or 3D arrays, or more. e.g., here's a 2D array:

B = np.array([[1,2,3],[4,5,6],[7,8,9]])
B.shape
(3, 3)

An array has methods, for example here's how to calculate the standard deviation:

A.std()
0.816496580928

A.std is a function, so to call it and get an answer we use (). It takes no arguments, but it knows to work on A because it is part of A.

Type A. and press the tab key to see what else an array can do. It's rather a lot.

Everything in Python is an object. Even integers and lists. Figure out what you can do with a list.

Task 4: Properties and methods

These questions require you to create an object of the specified type, and then use x. followed by the TAB key to see what properties and methods it has. Try things. Explore.

Type question mark ? after the object or methor and press ENTER to get information about it.

Plotting

To plot curves in Python, we need to import a plotting library. Here, we use one specific part of the larger matplotlib library:

import matplotlib.pyplot as plt

We can now plot like so:

plt.plot(x,y)
[<matplotlib.lines.Line2D object at 0x7f78146279e8>]

Task 5: Plotting

Plot the function \(y=\cos(2\pi t)e^{-t}\) for \(t\) between \(0\) and \(10\).

Hint: use np.cos and np.exp.

Call a demonstrator to check once you've made a plot.

Outlook

Python can load spreadsheet-like data np.loadtxt and pick out columns, rows, or any rectangular section (slicing).

Enter an equation with free parameters e.g. \(f(x,m,c) = mx+c\) and Python can find the best-fit values via curve_fit.

def f(x,m,c):
    return m*x + c

from scipy.optimize import curve_fit
xdata = [1,2,3,4]
ydata = [2,4,5,9]
guess = [1,0]
best_fit, covariance = curve_fit(f, xdata, ydata, p0=guess)

best_fit
[ 2.2 -0.5]

Python can perform numerical integrals, which occur very often in physics quad or trapz i.e. you can write down the integral from the physics, but it may be difficult to solve analytically.

from scipy.integrate import quad
def y(x):
    return np.exp(-x**2)/np.sqrt(np.pi)

quad(y,-10,10)
(0.9999999999999999, 2.085073301853646e-13)

Python can simulate differential equations, which are everywhere in physics, from Newton's laws \(F=ma=m\ddot{x}\) to quantum mechanics \(\hat{H}\psi = -i\hbar \partial_t \psi\).

Python can make changes to files, talk over the network, automate tedious tasks, etc.

Skills learned in Python are transferrable to other languages. Programming is an extremely employable skill.

The end

How to install

If you're on Windows or Mac, the consensus is that Anaconda is the easiest to get started. This includes most of the modules you're likely to want. If you're in Linux (Debian family, including Ubuntu) then Python is already installed and the tools we've used today can be installed with the following command:

sudo apt install spyder3 ipython3 python3-matplotlib python3-scipy python3-sympy

Tutorials

There are lots of on-line Python tutorials, a list of which is here. See also the official tutorial.

For scientific computing, excellent notes are here.

e.g. fitting a theoretical curve to data.

Useful modules