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: %% Cell type:markdown id: tags:
# Introduction to Python Programming # Introduction to Python Programming
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## 1. Getting Started ## 1. Getting Started
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
#### Running Python #### Running Python
%% Cell type:markdown id: tags: %% 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. 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: %% 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. 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: %% 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. 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: %% Cell type:markdown id: tags:
![An example of the IPython-Qtshell window](images/IPythonQtShell.png) ![An example of the IPython-Qtshell window](images/IPythonQtShell.png)
%% Cell type:markdown id: tags: %% 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.) 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: %% 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. 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: %% 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). 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: %% Cell type:code id: tags:
``` python ``` python
print('Hello, World') print('Hello, World')
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# type your command(s) here or use the IPython shell... # type your command(s) here or use the IPython shell...
``` ```
%% Cell type:markdown id: tags: %% 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. 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: %% Cell type:markdown id: tags:
#### Playing with Python #### Playing with Python
%% Cell type:markdown id: tags: %% 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. 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: %% 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. 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: %% 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. 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: %% 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. 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: %% 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. 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: %% Cell type:markdown id: tags:
#### Evaluating Expressions #### Evaluating Expressions
%% Cell type:markdown id: tags: %% 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. 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: %% Cell type:markdown id: tags:
Have a go with some expressions, such as: Have a go with some expressions, such as:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
3 * 4 # Multiplication 3 * 4 # Multiplication
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# type your command(s) here or use the IPython shell... # type your command(s) here or use the IPython shell...
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
7 + 10 # Addition 7 + 10 # Addition
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# type your command(s) here or use the IPython shell... # type your command(s) here or use the IPython shell...
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
7 - 10 # Subtraction 7 - 10 # Subtraction
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# type your command(s) here or use the IPython shell... # type your command(s) here or use the IPython shell...
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
10 / 2 # Division 10 / 2 # Division
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# type your command(s) here or use the IPython shell... # type your command(s) here or use the IPython shell...
``` ```
%% Cell type:markdown id: tags: %% 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: 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: %% Cell type:code id: tags:
``` python ``` python
10 % 3 # Modulus (remainder) 10 % 3 # Modulus (remainder)
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# type your command(s) here or use the IPython shell... # type your command(s) here or use the IPython shell...
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
2 ** 10 # Exponentiation (2 to the power of 10) 2 ** 10 # Exponentiation (2 to the power of 10)
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# type your command(s) here or use the IPython shell... # type your command(s) here or use the IPython shell...
``` ```
%% Cell type:markdown id: tags: %% 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: 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: %% Cell type:code id: tags:
``` python ``` python
10 / 7 10 / 7
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# type your command(s) here or use the IPython shell... # type your command(s) here or use the IPython shell...
``` ```
%% Cell type:markdown id: tags: %% 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: 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: %% Cell type:code id: tags:
``` python ``` python
10.0 / 7 10.0 / 7
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# type your command(s) here or use the IPython shell... # type your command(s) here or use the IPython shell...
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
10 / 7.0 10 / 7.0
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# type your command(s) here or use the IPython shell... # type your command(s) here or use the IPython shell...
``` ```
%% Cell type:markdown id: tags: %% 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”: 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: %% Cell type:code id: tags:
``` python ``` python
10.0 // 7 10.0 // 7
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# type your command(s) here or use the IPython shell... # type your command(s) here or use the IPython shell...
``` ```
%% Cell type:markdown id: tags: %% 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: 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: %% Cell type:code id: tags:
``` python ``` python
2 ** 32 2 ** 32
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Python can deal with numbers slightly larger than this too, so Python can deal with numbers slightly larger than this too, so
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
2 ** 64 2 ** 64
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
and even and even
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
2 ** 1024 2 ** 1024
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
work just fine. You can go even higher, so raising to the power of 100,000 work just fine. You can go even higher, so raising to the power of 100,000
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
2 ** 100000 2 ** 100000
``` ```
%% Cell type:markdown id: tags: %% 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. 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: %% 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: 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: %% Cell type:code id: tags:
``` python ``` python
'Hello, ' + "world!" 'Hello, ' + "world!"
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# type your command(s) here or use the IPython shell... # type your command(s) here or use the IPython shell...
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
'Hello ' * 8 'Hello ' * 8
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# type your command(s) here or use the IPython shell... # type your command(s) here or use the IPython shell...
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
9 * 'Hello...' 9 * 'Hello...'
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# type your command(s) here or use the IPython shell... # type your command(s) here or use the IPython shell...
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
#### _Exercise 1.1_ #### _Exercise 1.1_
%% Cell type:markdown id: tags: %% 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? 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: %% Cell type:markdown id: tags:
a) a)
```Python ```Python
(12*2 + 5*2)/2 (12*2 + 5*2)/2
``` ```
b) b)
```Python ```Python
(12**2 + 5**2)**0.5 (12**2 + 5**2)**0.5
``` ```
c) c)
```Python ```Python
(12^2 + 5^2)^0.5 (12^2 + 5^2)^0.5
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# type your command(s) here or use the IPython shell... # type your command(s) here or use the IPython shell...
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
#### Using Variables #### Using Variables
%% Cell type:markdown id: tags: %% 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: 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: %% Cell type:code id: tags:
``` python ``` python
x = 3 x = 3
``` ```
%% Cell type:markdown id: tags: %% 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: 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: %% Cell type:code id: tags:
``` python ``` python
y = 10.0 / 7 y = 10.0 / 7
``` ```