Python Notes

My notes from working through Chapter 2 of Newman's Computational Physics


In [1]:
print("Hello World")


Hello World

Variable Types


In [2]:
x=1
print(x)


1

You can make a float either by just assiging the variable, or by specifying with the x=float() command.


In [3]:
x=1.5
print(x)
x=float(1)
print(x)


1.5
1.0

In [4]:
x=complex(1.5)
print(x)


(1.5+0j)

In [5]:
x="This is a string"
print(x)


This is a string

Tips for Formatting Output


In [6]:
x=1
y=2
print("The value of x is",x,"and the value of y is",y)


The value of x is 1 and the value of y is 2

In [7]:
x=1.0
y=2.0
print("The value of x is",x,"and the value of y is",y)


The value of x is 1.0 and the value of y is 2.0

Inputting stuff


In [1]:
y = input("Enter the value of y: ")
print(y)


Enter the value of y: 10
10

In [2]:
x = input("Enter the value of x: ")
print(x)


Enter the value of x: Hello world
Hello world
  • Specify the type of the input variable

In [3]:
x = float(input("Enter the value of x: "))
print("The value of x is",x)


Enter the value of x: HEllo

ValueErrorTraceback (most recent call last)
<ipython-input-3-8cfe287bccb6> in <module>()
----> 1 x = float(input("Enter the value of x: "))
      2 print("The value of x is",x)

ValueError: could not convert string to float: 'HEllo'

Basic Maths


In [4]:
a=2
b=2
x=a+b
print(x)


4

In [5]:
x=a+2*b
print(x)


6

In [6]:
c=1
x = a + b/c
print(x)
x = (a + b)/c
print(x)
x = a + 2*b - 0.5*(1.618**c + 2/7)
print(x)


4.0
4.0
5.048142857142857

Python Modifiers


In [7]:
x,y = 1,2.5
print(x+y)


3.5

In [8]:
x +=1
print(x)


2

In [9]:
x +=1
print(x)


3

In [ ]:
x,y=y,x
print(x,y)

Dropping a Ball from a Tower


In [6]:
h = float(input("Enter the height of the tower: "))
g=9.81
t=(2.0*h/g)**0.5
print("The ball will hit the ground after",t,"seconds")


Enter the height of the tower: 10
The ball will hit the ground after 1.4278431229270645 seconds

Example of Using Math Functions


In [5]:
from math import sin,cos,pi

print("This program will convert from r,theta to x,y co-ordinates")
r = float(input("Enter r: "))
d = float(input("Enter theta in degrees: "))

theta = d*pi/180
x = r*cos(theta)
y = r*sin(theta)
print("x =",x," y =",y)


This program will convert from r,theta to x,y co-ordinates
Enter r: 8
Enter theta in degrees: 10
x = 7.878462024097664  y = 1.3891854213354426

Examples of If and While Statements


In [2]:
x = int(input("Enter a whole number no greater than ten: "))
while x>10:
            print("This is greater than ten.  Please try again.")
            x = int(input("Enter a whole number no greater than ten: "))
print("Your number is",x)


Enter a whole number no greater than ten: 11
This is greater than ten.  Please try again.
Enter a whole number no greater than ten: 7
Your number is 7

In [3]:
x = int(input("Enter a whole number no greater than ten: "))
if x>10:
       print("You entered a number greater than ten.")
       print("Let me fix that for you.")
       x = 10
print("Your number is",x)


Enter a whole number no greater than ten: 14
You entered a number greater than ten.
Let me fix that for you.
Your number is 10

In [11]:
n = int(input("Enter an Integer: "))
if n%2==0: 
        print("even")
else: 
        print("odd")


Enter an Integer: 8
even

Now check two intergers


In [12]:
print("Enter two integers, one even, one odd.")
m=int(input("Enter the first integer: "))
n=int(input("Enter the second integer: "))
while (m+n)%2==0:
        print("One must be even the other odd.")
        m=int(input("Enter the first integer: "))
        n=int(input("Enter the second integer: "))
print("The numbers you chose are", m, "and", n)


Enter two integers, one even, one odd.
Enter the first integer: 8
Enter the second integer: 7
The numbers you chose are 8 and 7

Example 2.4: The Fibonacci Sequence

The sequence of integers in which each is the sum of the previous two. E.g. 1 1 2 3 5 8 etc. The sequence up to the value of 1000 would take ages to calculate by hand, but it's quick in code


In [13]:
f1 = 1
f2 = 2
next = f1 + f2
while f1<=1000:
    print(f1)
    f1=f2
    f2=next
    next=f1+f2


1
2
3
5
8
13
21
34
55
89
144
233
377
610
987

In [14]:
f1,f2 = 1,1
while f1 <= 1000: 
    print(f1)
    f1,f2 = f2,f1+f2


1
1
2
3
5
8
13
21
34
55
89
144
233
377
610
987

Lists and Arrays

Get used to starting counting from zero!

The most basic containier in python is the list - a set of numbers associated with each other.

Example 1: A 3 component vector as a list


In [16]:
from math import sqrt
r = [1.0, 1.5, -2.2]
length = sqrt(r[0]**2 + r[1]**2 + r[2]**2)
print(length)


2.8442925306655784

In [17]:
total=sum(r)
print(total)


0.2999999999999998

In [18]:
mean=sum(r)/len(r)
print(mean)


0.09999999999999994

Applying functions to lists

Make use of the meta function "map" which allowes a function to be applied to all elements of a list at once.

The below may seems a bit strange, but it's done to save memory - the map(log,r) does not save, until you put it into a list.


In [22]:
from math import log
r=[1.0,1.5,2.2]
logr = list(map(log,r))
print(logr)


[0.0, 0.4054651081081644, 0.7884573603642703]

Append

Append is a really useful function with a list - allows values to be added to the list, which is something you'll do all the time in physics coding.


In [23]:
r.append(6.1)
print(r)


[1.0, 1.5, 2.2, 6.1]

To make an empty list (must make an empty list before adding elements to it.


In [8]:
r=[]
r.append(1.0)
r.append(1.5)
r.append(-2.2)
print(r)


[1.0, 1.5, -2.2]

To remove a value from the end of a list:


In [9]:
r.pop()
print(r)


[1.0, 1.5]

Arrays

  • Lists can be added to with append, arrays have fixed lengths.
  • Lists can have mixed types, arrays are all the same type (good for debugging).
  • Arrays can be 2D (e.g. images).
  • Arrays behave like vectors or matrices (not true with lists).

In [25]:
from numpy import zeros
a = zeros(4,float)
print(a)


[ 0.  0.  0.  0.]

In [26]:
a=zeros([3,4],float)
print(a)


[[ 0.  0.  0.  0.]
 [ 0.  0.  0.  0.]
 [ 0.  0.  0.  0.]]

In [27]:
from numpy import empty
a=empty(4,float)
print(a)


[ 0.  0.  0.  0.]

In [28]:
from numpy import zeros
a=zeros([2,2],int)
a[0,1]=1
a[1,0]=-1
print(a)


[[ 0  1]
 [-1  0]]

Making an array with arange:


In [14]:
from numpy import arange
x=arange(1,11,1)
print(x)


[ 1  2  3  4  5  6  7  8  9 10]

In [15]:
x=arange(1.0,11.0,2.0)
print(x)


[ 1.  3.  5.  7.  9.]

Now linspace - which is similar, but not identical


In [17]:
from numpy import linspace
x=linspace(1,100.0,10)
print(x)


[   1.   12.   23.   34.   45.   56.   67.   78.   89.  100.]

Reading from a File

(Something you will do all the time in physics)


In [10]:
from numpy import loadtxt
a = loadtxt("values.txt",float)
print(a)


[ 1.   1.5 -2.2  2.6]

Arithmetic with arrays


In [32]:
from numpy import array
a = array([1,2,3,4],int)
print(a+1)


[2 3 4 5]

In [33]:
a = array([1,2,3,4],int)
b = array([2,4,6,8],int)
print(a*b)


[ 2  8 18 32]

For dot products need to use special function


In [35]:
from numpy import array,dot
print(dot(a,b))


60

Finding the size of an array


In [37]:
a = array([[1,2,3],[4,5,6]],int)
print(a.size)
print(a.shape)


6
(2, 3)

Slicing

If r is a list, then r[m:n] is a subset of the list starting with element m, and going up to but not including element n.


In [39]:
r=[1,3,5,7,9,11,13,15]
s=r[2:5]
print(s)


[5, 7, 9]

For Loops


In [40]:
r=[1,3,5]
for n in r: 
    print(n)
    print(2*n)
print("Finished")


1
2
3
6
5
10
Finished

In [41]:
r=range(5)
for n in r:
    print("Hello again")


Hello again
Hello again
Hello again
Hello again
Hello again

In [44]:
for n in range(5):
    print(n**2)


0
1
4
9
16

Variants of range:


In [45]:
for n in range(5):
    print(n)


0
1
2
3
4

In [47]:
for n in range(2,8):
    print(n)


2
3
4
5
6
7

In [48]:
for n in range(2,20,3):
    print(n)


2
5
8
11
14
17

In [50]:
for n in range(20,2,-3):
    print(n)


20
17
14
11
8
5

Range must be integers (so the below won't work)


In [11]:
p=10
q=2
for n in range(p/q):
    print(n)


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-11-865f03022812> in <module>()
      1 p=10
      2 q=2
----> 3 for n in range(p/q):
      4     print(n)

TypeError: 'float' object cannot be interpreted as an integer

Make use of integer division


In [12]:
for n in range (p//q):
    print(n)


0
1
2
3
4

Example: The Emission Lines of Hydrogen

Please work through this example to check you understand lists and arrays.

The wavelengths of emission lines in the spectrum of hydrogen are given by the Rydberg Formula:

$\frac{1}{\lambda} = R ( \frac{1}{m^2} - \frac{1}{n^2} )$

were $R$ is the Rydberg constant, $R = 1.097 \times 10^{-2}$, and $m$ and $n$ are the energy levels of the transition.

We can write a programme to calculate all the emission lines very easilly.

First do this using for loops, then using lists and "for" commands.

Format the output to have 3 decimal places.

~

~

~

~

~

~

~


In [19]:
R = 1.097e-2
for m in [1,2,3]:
    print("Series for m = ",m)
    for k in [1,2,3,4,5]:
        n=k+m
        invlambda = R*(1/m**2 - 1/n**2)
        print("   ", 1/invlambda, " nm ")


Series for m =  1
    121.5436037678517  nm 
    102.55241567912488  nm 
    97.23488301428137  nm 
    94.95594044363415  nm 
    93.76220862091418  nm 
Series for m =  2
    656.3354603463993  nm 
    486.1744150714068  nm 
    434.084299170899  nm 
    410.2096627164995  nm 
    397.04243897498225  nm 
Series for m =  3
    1875.2441724182836  nm 
    1281.9051959890612  nm 
    1093.8924339106654  nm 
    1005.013673655424  nm 
    954.6697605038536  nm 

Quicker method using range


In [20]:
R = 1.097e-2
for m in range(1,4):
    print("Series for m = ",m)
    for n in range(m+1,m+6):
        invlambda = R*(1/m**2 - 1/n**2)
        print("   ",1/invlambda, " nm")


Series for m =  1
    121.5436037678517  nm
    102.55241567912488  nm
    97.23488301428137  nm
    94.95594044363415  nm
    93.76220862091418  nm
Series for m =  2
    656.3354603463993  nm
    486.1744150714068  nm
    434.084299170899  nm
    410.2096627164995  nm
    397.04243897498225  nm
Series for m =  3
    1875.2441724182836  nm
    1281.9051959890612  nm
    1093.8924339106654  nm
    1005.013673655424  nm
    954.6697605038536  nm

In [ ]: