This first lab sheet will introduce you to programming. You are expected to work through the tutorial and the worked example. worked example. There are other exercises that aim to push your understanding further. Finally at the end of the sheet there are links to other resources and tutorials that you might find helpful and/or interesting.
There are videos throughout the sheets describing the concepts as well as showing demos.
Here is an overview of the course.
Python is a programming language. There are various other programming languages:
A programming language allows you to write a program which is a sequence of instructions that specifies how to perform a computation.
When writing a program you need two things:
We will be using a combination of these 2 things called notebooks.
There are various distributions of Python, we will use Anaconda which comes packaged with a variety of other useful tools (including the notebooks I mentioned above).
To install it on your personal machine follow these steps:
We will use a Jupyter notebook which runs in your browser. To open a local server find the Continuum navigator and click on Jupyter. You do not need to be connected to the internet to use this.
This video is a demo of using a notebook.
These lab sheets will include code snippets. They show what code you should write but also the output you should see. Try the following:
In [1]:
print("Hello world")
Work through the following:
A video describing the concept.
One of the building block of any programming language is variables. This is how we store a particular variable that we can reuse:
In [2]:
age = 20
age
Out[2]:
It is possible to carry out a variety of numeric operations and reassigning the value of the variable:
In [3]:
age = age + 1 # Adding 1 to age
age
Out[3]:
Python has some short hand for the above:
In [4]:
age += 1 # Adding 1 to age
age
Out[4]:
We can do more than just addition (experiment with these as you might need them later on):
-
*
/
**
%
We can check the type of our variables, this can be particularly helpful when trying to understand errors and/or undexpected behaviour:
In [5]:
type(5) # An integer
Out[5]:
In [6]:
type(5.4) # A 'float'
Out[6]:
Experiment with manipulating numeric variables.
A video describing the concept.
Another type of variable used is called a character variable. In programming these are called strings.
In [7]:
firstname = "Vince"
firstname
Out[7]:
In [8]:
type(firstname)
Out[8]:
We can also create new strings from other ones:
In [9]:
lastname = "Knight"
fullname = firstname + " " + lastname
fullname
Out[9]:
Experiment by creating your own strings variables.
A video describing the concept.
Programming languages can be used to check if statements are true or not. A
variable that can either be True
or False
is called a boolean variable.
Here is a simple example:
In [10]:
a = 4
b = 8 / 2
a == b # Check if a is equal to b
Out[10]:
In [11]:
a != b # Check if a is NOT equal to b
Out[11]:
In [12]:
a >= b # Check if a is bigger or equal to b
Out[12]:
In [13]:
a < b + 1 # Check if a is stricly smaller than b + 1
Out[13]:
Note that we can set the statement to be a variable itself:
In [14]:
statement = a == b
statement
Out[14]:
In [15]:
type(statement)
Out[15]:
We can use this to carry out different operations depending on whether or not a boolean is True or False.
In [16]:
n = 11
if n <= 5: # Experiment by changing the value of n
value = 1
elif n % 2 == 0: # Otherwise if (else if)
value = 2
else: # Otherwise
value = 3
value
Out[16]:
The indentation is important: everything indented after the if
, elif
,
else
statements is what will be evaluated in that specific case.
The above is in essence producing:
$$f(n)=\begin{cases} 1&\text{ if } n\leq 5\\ 2&\text{ if } n> 5\text{ and } n \text{ even}\\ 3&\text{ otherwise }\\ \end{cases}$$Experiment by changing the function $f$ and modifying the code.
A video describing the concept.
It is possible to use code to repeat various actions. Here is a while
loop
that repeats whatever is indented until the boolean condition is no longer
true:
In [17]:
count = 0 # A variable to count
total = 0 # We will sum the first ten numbers
while count < 10: # Keep repeating until count if >= 10
count += 1 # Adding 1 to count
total += count # Adding the count to the total
total
Out[17]:
Experiment by summing (or perhaps multiplying?) over a different list of items.
A video describing the concept.
This is a slightly more complex example that brings together the various concepts above.
Let us aim to verify (this is not a proof!) that the following statement is true:
$$ \sum_{i=0}^n i ^ 2 = \frac{n(n+1)(2n+1)}{6} $$We will do this by computing the left hand side and the right hand side:
In [18]:
n = 20
rhs = n * (n + 1) * (2 * n + 1) / 6
lhs = 0
i = 0
while i < n:
i += 1
lhs += i ** 2
lhs == rhs
Out[18]:
We can put all of the above in a while
loop that will check it for a large number of values of n:
In [19]:
max_n = 2000
n = 0
while n < max_n:
n += 1
rhs = n * (n + 1) * (2 * n + 1) / 6
lhs = 0
i = 0
while i < n:
i += 1
lhs += i ** 2
if lhs != rhs:
print(False)
Debugging exercise
Below is code that attempts to verify the following identity for all values less than 2000.
$$ \sum_{i=0}^ni ^ 3 = \frac{\left(n ^ 2 + n\right)^{2}}{4} $$There is at least one error (also called a bug) in the code. Find and fix all the bugs.
max_n = 2000
n = 0
while n > max_n:
n += 2
rhs = ((n ** 2 + 2 * n) ** 2) / 4
lhs = 0
i = 0
while i < n:
i += 1
lhs += i ** 2
if lhs != rhs:
print(False)
In [20]:
max_n = 2000
n = 0
#while n > max_n: This inequality is the wrong way around:
while n < max_n:
#n += 2 We should be incrementing by 1
n += 1
#rhs = ((n ** 2 + 2 * n) ** 2) / 4 This is the incorrect formula
rhs = ((n ** 2 + n) ** 2) / 4
lhs = 0
i = 0
while i < n:
i += 1
#lhs += i ** 2 Incrementing the incorrect amount
lhs += i ** 3
if lhs != rhs:
print(False)
In [21]:
# Here is the right hand side:
n = 20
rhs = n * (n + 1) / 2
rhs
Out[21]:
In [22]:
# Here is the left hand side:
lhs = 0
i = 0
while i < n:
i += 1
lhs += i # This is the only line that is different to before
lhs
Out[22]:
In [23]:
lhs == rhs
Out[23]:
In [24]:
max_n = 2000
n = 0
while n < max_n: # checking the equality for n up until 2000
n += 1
rhs = n * (n + 1) / 2
lhs = 0
i = 0
while i < n:
i += 1
lhs += i
if lhs != rhs:
print(False) # Will print a False if it ever finds an error
In [25]:
upper_limit = 1000
total = 0
number = 0
while number < upper_limit:
number += 1 # Increment the number
if number % 3 != 0: # Check if it is divisible by 3
total += number
total
Out[25]:
In [26]:
upper_count = 1000
total = 0
number = 0
count = 0
while count < upper_count:
number += 1 # Increment the number
if number % 3 != 0: # Check if it is divisible by 3
total += number
# Keep track of how many numbers we have that are divisible by 3
count += 1
total
Out[26]:
In [27]:
epsilon = 0.001
K = 92 #This sets an initial value to take the square root of
X = K / 4.0 # This picks an initial value for the sequence
while abs(X**2 - K) > epsilon: # abs is the absolute value
X = (X + K / X) / 2
print(X)
In [28]:
# Let us check:
round(X ** 2, 3)
Out[28]: