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

cleared output from cells

parent 7374e006
This diff is collapsed.
......@@ -82,34 +82,22 @@
``` python
'eggs' in shopping
```
%%%% Output: execute_result
True
%% Cell type:code id: tags:
``` python
'frogs' in shopping
```
%%%% Output: execute_result
False
%% Cell type:code id: tags:
``` python
'frogs' not in shopping
```
%%%% Output: execute_result
True
%% Cell type:markdown id: tags:
We can use this in a new Python statement, which allows us to only execute statements if a particular condition is true. Back in the editor window, the program could be changed to:
%% Cell type:code id: tags:
......@@ -147,14 +135,10 @@
``` python
range(10)
```
%%%% Output: execute_result
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
%% Cell type:markdown id: tags:
So, as you will see from the output, a loop like this:
%% Cell type:code id: tags:
......@@ -273,14 +257,10 @@
``` python
s = 'I need to buy {} {}'.format(7, 'snakes')
s
```
%%%% Output: execute_result
'I need to buy 7 snakes'
%% Cell type:markdown id: tags:
Don't we all? In the example above, we didn't place anything inside the curly brackets, so the values of the variables provided as arguments to the `format()` method were inserted in the order and format that they were given. However, you can specify the order of insertion by including a number between the curly brackets, like so:
%% Cell type:code id: tags:
......@@ -288,14 +268,10 @@
``` python
s = 'I need to buy {0} {1} because I have {0} {2}'.format(7, 'mice', 'snakes to feed')
s
```
%%%% Output: execute_result
'I need to buy 7 mice because I have 7 snakes to feed'
%% Cell type:markdown id: tags:
The placeholders can also contain information for formatting the inserted value. For example, to control the number of level of precision on a floating point number, you can use `{:.Nf}` where `N` is the number of places that you want to display.
%% Cell type:code id: tags:
......@@ -306,14 +282,10 @@
s = 'Each mouse costs EUR {:.2f} and I need {} mice, so the total cost will be EUR {:.2f}'\
.format(mousePrice, numberOfMice, mousePrice*numberOfMice)
s
```
%%%% Output: execute_result
'Each mouse costs EUR 9.50 and I need 7 mice, so the total cost will be EUR 66.50'
%% Cell type:markdown id: tags:
There are a lot of other formatting options that can be controlled by these patterns in placeholders e.g. you can automatically print large numbers split with commas, or you can print text in clearly-defined columns buffered with whitespace. For a full list and explanation, you should check out the Python documentation at https://docs.python.org/2/library/string.html#format-string-syntax.
%% Cell type:markdown id: tags:
......@@ -342,14 +314,10 @@
'Maths in the Living Environment': 0
}
studentNumbers['Bioscience Technology']
```
%%%% Output: execute_result
16
%% Cell type:markdown id: tags:
The data is enclosed in curly brackets and is a comma separated list of key-value pairs. The key and value are separated by `:`. The key can be any immutable type (so, mainly strings, numbers or tuples). Notice I have split the assignment statement to create the dictionary over several lines, to make it easier to read. Normally, Python expects a command to be on a single line, but sometimes it recognises that a command isn’t finished and lets you continue on the next line. This mainly happens when you haven’t closed a set of brackets, which in the above example was deliberate, but in my case is usually because I have forgotten. Python will continue to prompt for input until you close the bracket properly before trying to execute the command.
%% Cell type:markdown id: tags:
......@@ -361,14 +329,10 @@
``` python
studentNumbers['Bioscience Technology'] += 1 # x += 1 does the same as x = x + 1
studentNumbers['Bioscience Technology']
```
%%%% Output: execute_result
17
%% Cell type:markdown id: tags:
If you try to assign a value to a key that doesn’t exist, Python creates the entry for you automatically:
%% Cell type:code id: tags:
......@@ -376,14 +340,10 @@
``` python
studentNumbers['Gardening'] = 10
studentNumbers['Gardening']
```
%%%% Output: execute_result
10
%% Cell type:markdown id: tags:
Getting rid of entries in the dictionary is easy as well, using the `del` statement:
%% Cell type:code id: tags:
......@@ -391,36 +351,20 @@
``` python
del studentNumbers['Maths in the Living Environment']
studentNumbers
```
%%%% Output: execute_result
{'Bioscience Technology': 17,
'Computational Biology': 12,
'Ecology and Environmental Management': 3,
'Gardening': 10,
'Post-Genomic Biology': 20}
%% Cell type:markdown id: tags:
If we know the keys in the dictionary we can look up the values. If we want to loop over the values in the dictionary, we could create a list of the keys and loop over that, but that’s no better than keeping the keys and values in separate lists. Instead, Python can create a list of the keys for you when you need it:
%% Cell type:code id: tags:
``` python
studentNumbers.keys()
```
%%%% Output: execute_result
['Gardening',
'Computational Biology',
'Post-Genomic Biology',
'Bioscience Technology',
'Ecology and Environmental Management']
%% Cell type:markdown id: tags:
We can now put this into a `for` loop, with or without sorting it first. If we are not bothered about the order, then we can just loop directly over the dictionary:
%% Cell type:code id: tags:
......@@ -442,28 +386,16 @@
``` python
studentNumbers.values()
```
%%%% Output: execute_result
[10, 12, 20, 17, 3]
%% Cell type:code id: tags:
``` python
studentNumbers.items()
```
%%%% Output: execute_result
[('Gardening', 10),
('Computational Biology', 12),
('Post-Genomic Biology', 20),
('Bioscience Technology', 17),
('Ecology and Environmental Management', 3)]
%% Cell type:markdown id: tags:
Have a careful look at this output. The square brackets show that this is a list of things. But each item in that list is in fact two pieces of data in round brackets. We came across this briefly above, and it is a tuple. There are two ways we can use this in a `for` loop. Firstly, we can use a variable which will contain the tuple and unpack it in body of the loop:
%% Cell type:code id: tags:
......@@ -534,14 +466,10 @@
``` python
square(3)
```
%%%% Output: execute_result
9
%% Cell type:markdown id: tags:
If you wanted to store the result in a variable, you could use
%% Cell type:code id: tags:
......@@ -559,14 +487,10 @@
``` python
z = square(y)
z
```
%%%% Output: execute_result
81
%% Cell type:markdown id: tags:
Functions are incredibly versatile and a single function may take many arguments. They can contain more than one line of code, and can do anything that you can do in other parts of a Python program. You will see a much more complex example in Worksheet 3. Parcelling up code like this means that you don’t have to type it out every time the task is repeated in your program, and if you need to change it, it will only have to be changed once.
%% Cell type:markdown id: tags:
......
......@@ -190,40 +190,23 @@
line = 'A\t29304'
taxonID, count = line.split('\t')
count
```
%%%% Output: execute_result
'29304'
%% Cell type:code id: tags:
``` python
count = count + 99
```
%%%% Output: error
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-9-e0cb6e716f7d> in <module>()
----> 1 count = count + 99
TypeError: cannot concatenate 'str' and 'int' objects
%% Cell type:code id: tags:
``` python
count = 29304
count
```
%%%% Output: execute_result
29304
%% Cell type:code id: tags:
``` python
count = count + 99
```
......@@ -237,14 +220,10 @@
``` python
count = int(count)
count
```
%%%% Output: execute_result
29403
%% Cell type:markdown id: tags:
to convert to an integer and, if needed, you could convert it back again with:
%% Cell type:code id: tags:
......@@ -252,14 +231,10 @@
``` python
count = str(count)
count
```
%%%% Output: execute_result
'29403'
%% Cell type:markdown id: tags:
Now when you add the lines to your program, you have variables containing the site name, the taxonID and the count (which you can now make sure is converted to a proper integer). You can put these into the dictionary of dictionaries like this:
%% Cell type:code id: tags:
......@@ -339,38 +314,20 @@
``` python
variable = studentNumbers # this is the dictionary from Worksheet 2
pp.pprint(variable)
```
%%%% Output: error
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-18-664fa7f1b946> in <module>()
----> 1 variable = studentNumbers # this is the dictionary from Worksheet 2
2 pp.pprint(variable)
NameError: name 'studentNumbers' is not defined
%% Cell type:markdown id: tags:
Compare this output to the way that the same dictionary is displayed by the default `print` function:
%% Cell type:code id: tags:
``` python
print studentNumbers
```
%%%% Output: error
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-19-256cd95918f4> in <module>()
----> 1 print studentNumbers
NameError: name 'studentNumbers' is not defined
%% Cell type:markdown id: tags:
I hope you'll agree that the `pprint` version is much easier to interpret by eye.
%% Cell type:markdown id: tags:
......@@ -437,70 +394,50 @@
``` python
plt.figure(1)
```
%%%% Output: execute_result
<matplotlib.figure.Figure at 0x1057d2050>
%% Cell type:markdown id: tags:
As soon as you executed this line, a new window might have appeared (it depends on your operating system) and this is where the figure will be drawn. Don’t worry if the window didn’t appear at this stage - it should show up when you’re done building the figure instead. Inline plotting is switched on in the IPython Notebook, so as we add things to the plot, you will see them appear below. The number argument to `plt.figure` is just a reference and lets you switch back to this figure later if you need to. The next step is to create a subplot. This is mostly used for figures with multiple panels, where each panel is a subplot. In this case, we’ll just do one for now, so we can just type one of the following statements:
%% Cell type:code id: tags:
``` python
plt.subplot(1,1,1)
```
%%%% Output: execute_result
<matplotlib.axes._subplots.AxesSubplot at 0x103e9b690>
%% Cell type:markdown id: tags:
or
%% Cell type:code id: tags:
``` python
plt.subplot(111)
```
%%%% Output: execute_result
<matplotlib.axes._subplots.AxesSubplot at 0x103e9b690>
%% Cell type:markdown id: tags:
These are again optional if you only have one panel in your figure, but again it’s generally better to be explicit. The arguments for the second form are (rows, columns, subfig), specifying the number of rows of panels, the number of columns and which one you want to draw now (which is in the range 1 - rows\*colums). So if you have twelve panels and you wanted to select the seventh, you would use one of
%% Cell type:code id: tags:
``` python
plt.subplot(3,4,7)
```
%%%% Output: execute_result
<matplotlib.axes._subplots.AxesSubplot at 0x1057d2110>
%% Cell type:markdown id: tags:
or
%% Cell type:code id: tags:
``` python
plt.subplot(4,3,7)
```
%%%% Output: execute_result
<matplotlib.axes._subplots.AxesSubplot at 0x103d47c10>
%% Cell type:markdown id: tags:
depending on how many rows and columns you used. Subfigures/subplots are numbered as if read like text: left-right and top-bottom. If rows\*columns is less than 10, you can use the top form without the commas e.g. `(321)` instead of `(3,2,1)`, but you might consider this to be less explicit.
%% Cell type:markdown id: tags:
......@@ -531,14 +468,10 @@
``` python
plt.bar(positions, barHeights)
```
%%%% Output: execute_result
<Container object of 20 artists>
%% Cell type:code id: tags:
``` python
plt.show() # you might need to run this line for your plot to appear
```
......
......@@ -297,28 +297,20 @@
``` python
AllGroupResults['Group C']
```
%%%% Output: execute_result
{'Alan': 61, 'Gareth': 74, 'Helen': 74, 'Laura': 91, 'Simon': 47}
%% Cell type:markdown id: tags:
But what if you want to know how a particular student scored? How can we access the value for a particular key in the dictionary that is itself the value associated with a key at the top level? Well, above we accessed the value associated with the key `'Group C'` using the syntax `dictionary[key]`. In this case, we know that that returns another dictionary. So, if we now want to get the score for a particular student in that group, we just query that dictionary in the same way.
%% Cell type:code id: tags:
``` python
AllGroupResults['Group C']['Laura']
```
%%%% Output: execute_result
91
%% Cell type:markdown id: tags:
If this looks strange to you, or you're struggling to make sense of it, remember that Python will interpret the line from left to right:
- first, it comes across the variable `AllGroupResults`, which it identifies as a dictionary
- then, it sees that you want to extract the value associated with the key `'Group C'`
......@@ -389,22 +381,10 @@
print("Kind regards,")
print('{}\n'.format(myName))
```
%%%% Output: error
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-35-6fcd1fe26c5f> in <module>()
1 # This is my solution. To be removed.
2 myName = 'Toby Hodges'
----> 3 for group in sorted(AllGroupResults.keys()):
4 for student in AllGroupResults[group]:
5 print('Dear {},'.format(student))
NameError: name 'AllGroupResults' is not defined
%% Cell type:markdown id: tags:
Of course, the potential for nested data structures doesn't stop at two-level lists of lists, or lists of dictionaries, or dictionaries of lists, or dictionaries of dictionaries! Depending on the situation, you might want to combine some of the other different structure types (which we don't cover so much here), build up three- or four-level structures, and so on. Be warned, though: with every additional layer, your program becomes more and more complicated. This makes it harder for you to keep track of what you're dealing with while you're writing it, harder to read when you or someone else comes back to the program at a later date, and more difficult to identify and correct mistakes in the code itself.
%% Cell type:markdown id: tags:
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment