Commit f6f6ae3e authored by Toby Hodges's avatar Toby Hodges
Browse files

added debugging exercise to worksheet 1.

parent e51b3eda
%% Cell type:markdown id: tags:
# Introduction to Python Programming
%% Cell type:markdown id: tags:
## 1. Getting Started
%% Cell type:markdown id: tags:
#### Running Python
%% Cell type:markdown id: tags:
Python itself normally exists just to run programs that you have written, but it can run as a program in its own right, allowing you to explore the language by typing commands which it then executes for you. Quite a lot can be done at this command prompt, but to do anything serious you will need to start creating your programs in a text editor and executing them with Python. However, we will start by looking at what you can do at the Python prompt.
%% Cell type:markdown id: tags:
When you install Anaconda, it creates a program group containing a few different items. Included in this are the IPython Console, 'ipython-qtconsole', which you should launch and use as your Python Shell (don't worry if you don't know what a shell is at this stage!). A second item, 'spyder', is a powerful text editor with the capacity to run your Python scripts in a dedicated shell window. You should launch this and use it when you start writing multi-line code that you will want to go back and edit/append as you go through the course.
%% Cell type:markdown id: tags:
Below is an example of the IPython QtConsole window. Yours might look slightly different from this, depending on the operating system that you are working in, but the functionality of the program itself remains (almost) exactly the same.
%% Cell type:markdown id: tags:
![An example of the IPython-Qtshell window](images/IPythonQtShell.png)
%% Cell type:markdown id: tags:
If you are running Linux or Mac OS X, start a terminal, type `ipython` and press return to get the same effect within the terminal window. (To leave the shell, type `exit()` and press enter.)
%% Cell type:markdown id: tags:
For this first worksheet, you can choose either to run the commands in the Python Shell or, if you are viewing this notebook interactively, you can execute your commands directly within the notebook code cells. We have inserted cells especially for you to play around with the code in. If you use these cells, you can execute the code within them with `CTRL+ENTER` and the output will be printed beneath the cell. Don't worry if you can't use this notebook interactively - you should just type all of the commands in the shell instead.
%% Cell type:markdown id: tags:
In the window image above, the `In[1]` is the Python prompt and it should have a flashing cursor. As is traditional under these circumstances, the first thing you should do is get Python to print out the text “Hello, World”. To do this, type the command below at the prompt and press return (control+return in the notebook).
%% Cell type:code id: tags:
``` python
print('Hello, World')
```
%% Cell type:code id: tags:
``` python
# type your command(s) here or use the IPython shell...
```
%% Cell type:markdown id: tags:
Barring the odd typing mistake you have just run your first Python script. Here, 'print' is a Python function that tells the interpreter that you want it to output the things which follow in the brackets. The 'Hello, World' is a _string_ and is what you want the `print` function to print out.
%% Cell type:markdown id: tags:
#### Playing with Python
%% Cell type:markdown id: tags:
The Python Shell is a great way to experiment with Python. It’s something that I return to every time I find myself thinking “I wonder what happens if you do this?” or “What’s the best way to do that?”. You can’t break anything by trying something out and if you do make a mistake, at least you will get an error message that you might be able to decode.
%% Cell type:markdown id: tags:
If you are viewing this notebook interactively (i.e. not through nbviewer), the code cells behave in a very similar way to the Shell prompt. You can play around with Python in the notebook's code cells (we have left some blank ones for you to try out your own commands in) and execute the cell once you are done typing. The output of your commands will appear underneath. If you have made a mistake, or you want to try something else, you can edit the code in the cell and execute it again when you're done.
%% Cell type:markdown id: tags:
You are not limited in what you can do at the prompt. You can load modules, look at them to see what they do, play with them. The first versions of the bar charts in Worksheet 3 were all produced at the python prompt, which enabled me to tweak them before writing the program to produce the whole figure. This meant I could see how they looked after every command and get them looking just as I wanted. I could also check the documentation for the modules I wanted to use by typing `help()`. There is a lot of information in there and you will find yourself using it again and again.
%% Cell type:markdown id: tags:
In addition to these features of the Python Shell, the IPython Shell has some very helpful features that can make things easier while you learn the basics of Python. For example, IPython enables tab-completion for e.g. variable, function, and file names, gives hints about required & optional arguments for functions, and has improved command history interaction.
%% Cell type:markdown id: tags:
For longer, multi-line programs you will probably find it easier to use a text editor, and we will cover that in Worksheet 2.
%% Cell type:markdown id: tags:
#### Evaluating Expressions
%% Cell type:markdown id: tags:
The Python shell can also be used to evaluate expressions, allowing you either to perform calculations interactively, or more usually to check more complicated expressions interactively before putting them in your programs. The Python shell allows you to do all of the normal operations, in pretty much the way you would expect.
%% Cell type:markdown id: tags:
Have a go with some expressions, such as:
%% Cell type:code id: tags:
``` python
3 * 4 # Multiplication
```
%% Cell type:code id: tags:
``` python
# type your command(s) here or use the IPython shell...
```
%% Cell type:code id: tags:
``` python
7 + 10 # Addition
```
%% Cell type:code id: tags:
``` python
# type your command(s) here or use the IPython shell...
```
%% Cell type:code id: tags:
``` python
7 - 10 # Subtraction
```
%% Cell type:code id: tags:
``` python
# type your command(s) here or use the IPython shell...
```
%% Cell type:code id: tags:
``` python
10 / 2 # Division
```
%% Cell type:code id: tags:
``` python
# type your command(s) here or use the IPython shell...
```
%% Cell type:markdown id: tags:
So far, so good, but don’t limit yourself to the examples here. Try some of your own and make sure you understand the results. There are a few other operators, though, which you might not be as familiar with. Try these:
%% Cell type:code id: tags:
``` python
10 % 3 # Modulus (remainder)
```
%% Cell type:code id: tags:
``` python
# type your command(s) here or use the IPython shell...
```
%% Cell type:code id: tags:
``` python
2 ** 10 # Exponentiation (2 to the power of 10)
```
%% Cell type:code id: tags:
``` python
# type your command(s) here or use the IPython shell...
```
%% Cell type:markdown id: tags:
Again, as expected. However, there are a few things that you need to be aware of when using arithmetic in any programming language. In Python v2.x, if your numbers are integers, Python with return an _integer_ value. So try:
%% Cell type:code id: tags:
``` python
10 / 7
```
%% Cell type:code id: tags:
``` python
# type your command(s) here or use the IPython shell...
```
%% Cell type:markdown id: tags:
Here you should get the answer 1.4285714285714286 if you're using Python v3.x, or 1 if you're using Python 2.x. This is one of the fundamental differences between the two versions of the language. The integer result might be what you want, and maybe you will pick up the remainder with the `%` operator. However, it might also be completely wrong. It’s easy to see when this is happening if you are typing the numbers into the expressions like this, but in the next section we’ll be assigning the numbers to variables and then it can be difficult to predict whether the number a variable refers to is an integer or not (though you will see later there are ways to check this). In either version, we can force Python to give us a non-integer result like this:
%% Cell type:code id: tags:
``` python
10.0 / 7
```
%% Cell type:code id: tags:
``` python
# type your command(s) here or use the IPython shell...
```
%% Cell type:code id: tags:
``` python
10 / 7.0
```
%% Cell type:code id: tags:
``` python
# type your command(s) here or use the IPython shell...
```
%% Cell type:markdown id: tags:
Of course, you might actually only want the integer result in the first place, and regardless of the version you can force Python to give you that as well using so-called “floor division”:
%% Cell type:code id: tags:
``` python
10.0 // 7
```
%% Cell type:code id: tags:
``` python
# type your command(s) here or use the IPython shell...
```
%% Cell type:markdown id: tags:
Python can handle some very large numbers. For example, it can easily deal with raising 2 to the power of 32:
%% Cell type:code id: tags:
``` python
2 ** 32
```
%% Cell type:markdown id: tags:
Python can deal with numbers slightly larger than this too, so
%% Cell type:code id: tags:
``` python
2 ** 64
```
%% Cell type:markdown id: tags:
and even
%% Cell type:code id: tags:
``` python
2 ** 1024
```
%% Cell type:markdown id: tags:
work just fine. You can go even higher, so raising to the power of 100,000
%% Cell type:code id: tags:
``` python
2 ** 100000
```
%% Cell type:markdown id: tags:
is quite OK. Though I must admit that I haven’t actually checked that the 30103 digits of this result are correct.
%% Cell type:markdown id: tags:
Some of these operators don’t just work on numbers, `+` and `*` can be used on strings as well. Strings are just sequences of characters enclosed in quotation marks like the 'Hello, World' above. Python doesn’t mind if you use single or double quotes as long as you don’t mix them. "Addition", `+`, concatenates two (or more) strings together to return a new longer string. "Multiplication", actually repetition, `*`, takes a number and a string and repeats the string that many times in a new string:
%% Cell type:code id: tags:
``` python
'Hello, ' + "world!"
```
%% Cell type:code id: tags:
``` python
# type your command(s) here or use the IPython shell...
```
%% Cell type:code id: tags:
``` python
'Hello ' * 8
```
%% Cell type:code id: tags:
``` python
# type your command(s) here or use the IPython shell...
```
%% Cell type:code id: tags:
``` python
9 * 'Hello...'
```
%% Cell type:code id: tags:
``` python
# type your command(s) here or use the IPython shell...
```
%% Cell type:markdown id: tags:
#### _Exercise 1.1_
%% Cell type:markdown id: tags:
Try to use expressions that you would use in your normal work and see if they give the results you expect. Explore using brackets to group sub-expressions (things in brackets are always evaluated before everything else). Before you move on to the next section, which of the following expressions would correctly calculate the hypotenuse of a right-angled triangle, with sides length 12 and 5?
%% Cell type:markdown id: tags:
a)
```Python
(12*2 + 5*2)/2
```
b)
```Python
(12**2 + 5**2)**0.5
```
c)
```Python
(12^2 + 5^2)^0.5
```
%% Cell type:code id: tags:
``` python
# type your command(s) here or use the IPython shell...
```
%% Cell type:markdown id: tags:
#### Using Variables
%% Cell type:markdown id: tags:
So far, we have just been playing with what Python calls values. When you are writing programs, it’s useful to be able to give names to the values that we are dealing with so that once we do a calculation or string manipulation we can refer to the results later. We do this with an assignment statement, which looks like this:
%% Cell type:code id: tags:
``` python
x = 3
```
%% Cell type:markdown id: tags:
You’ll notice that, when this line is executed, Python doesn’t return anything. This is also true if you capture the result of one of the expressions that we tried above:
%% Cell type:code id: tags:
``` python
y = 10.0 / 7
```
%% Cell type:markdown id: tags:
To look at the values, just type the names of the variables that you have created:
%% Cell type:code id: tags:
``` python
x
```
%% Cell type:code id: tags:
``` python
y
```
%% Cell type:markdown id: tags:
More normally, you would probably output the results using the `print` statement we started with. In Python version 2:
%% Cell type:code id: tags:
``` python
print x, y
```
%% Cell type:markdown id: tags:
Or in version 3:
%% Cell type:code id: tags:
``` python
print(x, y)
```
%% Cell type:markdown id: tags:
If the brackets are included in the output above, then you're working in version 2. If not, then you have a version 3 environment. (Whichever version you have, you will be able to work through the rest of this course.)
%% Cell type:markdown id: tags:
As well as being on the left of an assignment operation, variable names can be used in the expressions as well, so
%% Cell type:code id: tags:
``` python
x = x + y
```
%% Cell type:markdown id: tags:
replaces the value currently referred to by `x` with the new value obtained from adding the values of `x` and `y`.
%% Cell type:code id: tags:
``` python
x
```
%% Cell type:markdown id: tags:
Variables that refer to numbers are fine and are incredibly useful, but they are also one of the less interesting types of Python data. This is because they only have a value. Some variables are much more interesting, and string variables are a good example. To assign a string to a variable you follow the same basic syntax as before:
%% Cell type:code id: tags:
``` python
s = 'The quick brown fox jumps over the lazy dog'
```
%% Cell type:code id: tags:
``` python
print s
```
%% Cell type:markdown id: tags:
Again, you can just type the variable name or use it in a `print` statement, but what makes a variable containing a string more interesting is that it is one of Python’s object data types. This means that it doesn’t just passively hold the value of the string, it also knows about things you can do to the string. For example:
%% Cell type:code id: tags:
``` python
s.upper()
```
%% Cell type:markdown id: tags:
The `.` here indicates that the method is part of the string `s`, and the brackets indicate that we want to execute it. Here the brackets are empty, but later we will be using them to pass information into the methods. There are many things that strings can do with themselves, and if you look at the Python cheat sheet, you will see what they all are. Try using them on the string, for example:
%% Cell type:code id: tags:
``` python
s.capitalize()
```
%% Cell type:code id: tags:
``` python
s.title()
```
%% Cell type:markdown id: tags:
If you look at `s` itself after any of these, you’ll see it hasn’t changed, these object methods simply return a new version of the string with the appropriate transformation done to it which you can then store in another variable (or back in `s`) if you want to. This is because a string cannot be changed in place (in technical terms, it is _immutable_), only explicitly overwritten with a new value. So, to save the new version of the string, you can type the following:
%% Cell type:code id: tags:
``` python
s = s.title()
```
%% Cell type:markdown id: tags:
You can use almost any combination of letters and numbers in the variable names, but you can’t start a variable name with a number. You can’t include spaces (a space is one of the ways that Python can tell that the name is finished) but you can include underscore characters. Variable names can also begin with underscore, but these tend to be used under special circumstance which you will discover once you start learning about object-oriented programming.
%% Cell type:markdown id: tags:
#### _Exercise 1.2_
%% Cell type:markdown id: tags:
Use the .count() method on the string “The quick brown fox jumps over the lazy dog” to count the occurrences of the word “the”.
%% Cell type:code id: tags:
``` python
s = "The quick brown fox jumps over the lazy dog"
# type your command(s) here or use the IPython shell...
```
%% Cell type:markdown id: tags:
If this returns 1, how could you persuade it that it should be 2?
%% Cell type:code id: tags:
``` python
# type your command(s) here or use the IPython shell...
```
%% Cell type:markdown id: tags:
Once you have that sorted out, try
%% Cell type:markdown id: tags:
`s.split()`
%% Cell type:code id: tags:
``` python
# type your command(s) here or use the IPython shell...
```
%% Cell type:markdown id: tags:
and see if you can understand what it has done.
%% Cell type:markdown id: tags:
#### Lists
%% Cell type:markdown id: tags:
The last exercise returned a result which you might think looks unusual. My interpreter gave me:
%% Cell type:code id: tags:
``` python
s = "The quick brown fox jumps over the lazy dog"
s.split()
```
%% Cell type:markdown id: tags:
This result is in the form of a _list_ object. A list is exactly what you might expect based on the name. It’s a set of values (which can be numbers, strings, objects or even lists, but that is a bit advanced for now) that are kept in a specific order. You can create a new list using the same format as the result above:
%% Cell type:code id: tags:
``` python
shopping = ['bread', 'potatoes', 'eggs', 'flour', 'rubber duck', 'pizza', 'milk']
```
%% Cell type:markdown id: tags:
Like strings, lists are a type of object, and so they also have some methods associated with them, which you can use. However, unlike strings, these methods mostly change the list in place, rather than returning a new list. So, when you type
%% Cell type:code id: tags:
``` python
shopping.sort()
```
%% Cell type:markdown id: tags:
Python doesn’t return a value, but if you look at the list, you will see that the order of the items has changed.
%% Cell type:code id: tags:
``` python
shopping
```
%% Cell type:markdown id: tags:
This means that unlike strings, lists are _mutable_, and individual items and sets of items can be changed in place. If you decide you want to add items to the list, you can do it with the `.append()` method:
%% Cell type:code id: tags:
``` python
shopping.append('mayonnaise')
shopping
```
%% Cell type:markdown id: tags:
If you feel it’s important enough to go at the top of the list, you can use `.insert()` to insert the new item at a particular point and shuffle everything else up:
%% Cell type:code id: tags:
``` python
shopping.insert(0, 'mayonnaise')
shopping
```
%% Cell type:markdown id: tags:
Removing items from the list is just as easy - you use `.pop()` to do that. If you don’t give it an index, it will remove the last item in the list, otherwise `pop` removes the item with the index you specify and shuffles everything else up one position to close the gap. Give it a try, to remove one of the "mayonnaise" items in the shopping list.
%% Cell type:code id: tags:
``` python
# type your command(s) here or use the IPython shell...
```
%% Cell type:markdown id: tags:
#### Sequences
%% Cell type:markdown id: tags:
The two object types that we have talked about so far share a number of properties. Both strings and lists consist of ordered pieces of data. In the case of strings this is simple characters. In lists, the elements of the list can be of any object type.
%% Cell type:markdown id: tags:
For both lists and strings we might want to refer to a particular item or range of items in a string or list and we can do this easily:
%% Cell type:code id: tags:
``` python
words = s.split()
print(words[3])
```
%% Cell type:markdown id: tags:
You will see that "fox" is actually the fourth word and this is just one of the things that computers do that you have to get used to. The first element in a sequence has an index of 0, so
%% Cell type:code id: tags:
``` python
print(words[0])
```
%% Cell type:markdown id: tags:
gives you the first item in the list. This is referred to as zero-based indexing or offset numbering. Its origins are in programming languages where variables actually refer to the memory location of the start of the list, and now has just become a tradition. Negative indices are assumed to be relative to the end of the array, so
%% Cell type:code id: tags:
``` python
words[-1]
```
%% Cell type:markdown id: tags:
yields the final element in the list, in this case "dog". Of course, if we knew how long the sequence was, we could just use the number of the last element. For any sequence data type, `len()` will tell us how many elements it has:
%% Cell type:code id: tags:
``` python
len(words)
```
%% Cell type:code id: tags:
``` python
len(s)
```
%% Cell type:markdown id: tags:
So, since the sequences are indexed from zero, the last element, i.e. `words[-1]`, is the same as `words[len(words)-1]`.
%% Cell type:markdown id: tags:
#### _Exercise 1.3_
%% Cell type:markdown id: tags:
There are a few quirks to sequence indexing (apart from starting at 0), and I have tried to summarise these on the Python Cheat Sheet. Have a go with a few of the "Indices and Slices" and make sure you understand how they work. Then, instead of trying them o