Chapter 01: Variables, Conditional Statements and Loops

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.

Installing and running Python

Python is a programming language. There are various other programming languages:

  • Java
  • C
  • C++
  • Ruby
  • VBA
  • and many more.

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:

  • Something to save the code (a text editor for example)
  • Something to run the code

We will be using a combination of these 2 things called notebooks.

Install Python

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:

  1. Go to this webpage: www.continuum.io/downloads.
  2. Identify and download the version of Python 3 for your operating system (Windows, Mac OSX, Linux).
  3. Run the installer.

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")
Hello world

Tutorial

Work through the following:


1: Creating numeric variables.

A video describing the concept.

A video demo.

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]:
20

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]:
21

Python has some short hand for the above:

In [4]:
age += 1  # Adding 1 to age
age
Out[4]:
22

We can do more than just addition (experiment with these as you might need them later on):

  • Subtraction: -
  • Multiplication: *
  • Division: /
  • Exponentiation: **
  • Modulo division: %

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]:
int
In [6]:
type(5.4)  # A 'float'
Out[6]:
float

Experiment with manipulating numeric variables.


2: Creating character variables.

A video describing the concept.

A video demo.

Another type of variable used is called a character variable. In programming these are called strings.

In [7]:
firstname = "Vince"
firstname
Out[7]:
'Vince'
In [8]:
type(firstname)
Out[8]:
str

We can also create new strings from other ones:

In [9]:
lastname = "Knight"
fullname = firstname + " " + lastname
fullname
Out[9]:
'Vince Knight'

Experiment by creating your own strings variables.


3. Boolean variables and if statements.

A video describing the concept.

A video demo.

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]:
True
In [11]:
a != b # Check if a is NOT equal to b
Out[11]:
False
In [12]:
a >= b # Check if a is bigger or equal to b
Out[12]:
True
In [13]:
a < b + 1  # Check if a is stricly smaller than b + 1
Out[13]:
True

Note that we can set the statement to be a variable itself:

In [14]:
statement = a == b
statement
Out[14]:
True
In [15]:
type(statement)
Out[15]:
bool

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]:
3

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.


4. While loops.

A video describing the concept.

A video demo.

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]:
55

Experiment by summing (or perhaps multiplying?) over a different list of items.


Worked example

A video describing the concept.

A video demo.

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]:
True

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)

Exercises

Here are a number of exercises that are possible to carry out using the code concepts discussed:

  • Variable assignement: for example a = 5
  • Arithmetic manipulation: for example a += 2
  • Conditional statements: for example if a == 7:
  • While loops: for example while a <= 10:

Exercise 1

Debugging exercise

A video demo.

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)

Exercise 2

Use code to check the following identity:

$$ \sum_{i=0}^{n}i=\frac{n(n+1)}{2} $$

for $n=20$.


Exercise 3

Modify the above (Exercise 2) to check it for all values less than 2000.


Exercise 4

Calculate the sum of the first natural numbers less than 1000 that are not divisible by 3.


Exercise 5

Calculate the sum of the first 1000 natural numbers that are not divisible by 3.


Exercise 6

It can be shown (you are not required to check this) that the following sequence:

$$ x_{n+1}=\frac{x_n + K / x_{n}}{2} $$

approaches $\sqrt{K}$ as $n$ increases. Write some code to verify this to any given level of precision.

Previous

Next

Source code: @drvinceknight Powered by: Python Jupyter Mathjax Github pages Skeleton css