Skip to content
Snippets Groups Projects
Commit cef92d12 authored by Mark Jenkinson's avatar Mark Jenkinson
Browse files

Updated to include suggested edits from Michiel, Paul and Duncan

parent 2e342a15
No related branches found
No related tags found
No related merge requests found
%% Cell type:markdown id: tags:
# Basic python
This tutorial is aimed at briefly introducing you to the main language
features of python, with emphasis on some of the common difficulties
and pitfalls that are commonly encountered when moving to python.
When going through this make sure that you _run_ each code block and
look at the output, as these are crucial for understanding the
explanations. You can run each block by using _shift + enter_
(including the text blocks, so you can just move down the document
with shift + enter).
It is also possible to _change_ the contents of each code block (these pages are completely interactive) so do experiment with the code you see and try some variations!
## Contents
* [Basic types](#Basic-types)
- [Strings](#Strings)
+ [Format](#Format)
+ [String manipulation](#String-manipulation)
- [Tuples and lists](#Tuples-and-lists)
+ [Adding to a list](#Adding-to-a-list)
+ [Indexing](#Indexing)
+ [Slicing](#Slicing)
- [List operations](#List-operations)
+ [Looping over elements in a list (or tuple)](#Looping)
+ [Getting help](#Getting-help)
- [Dictionaries](#Dictionaries)
+ [Adding to a dictionary](#Adding-to-a-dictionary)
+ [Removing elements from a dictionary](#Removing-elements-dictionary)
+ [Looping over everything in a dictionary](#Looping-dictionary)
- [Copying and references](#Copying-and-references)
* [Control flow](#Control-flow)
- [Boolean operators](#Boolean-operators)
- [If statements](#If-statements)
- [For loops](#For-loops)
- [While loops](#While-loops)
- [A quick intro to conditional expressions and list comprehensions](#quick-intro)
+ [Conditional expressions](#Conditional-expressions)
+ [List comprehensions](#List-comprehensions)
* [Functions](#functions)
* [Exercise](#exercise)
---
<a class="anchor" id="Basic-types"></a>
# Basic types
Python has many different types and variables are dynamic and can change types (like MATLAB). Some of the most commonly used in-built types are:
* integer and floating point scalars
* strings
* tuples
* lists
* dictionary
* dictionaries
N-dimensional arrays and other types are supported through common modules (e.g., numpy, scipy, scikit-learn). These will be covered in a subsequent exercise.
%% Cell type:code id: tags:
``` python
a = 4
b = 3.6
c = 'abc'
d = [10, 20, 30]
e = {'a' : 10, 'b': 20}
print(a)
```
%% Output
4
%% Cell type:markdown id: tags:
Any variable or combination of variables can be printed using the function `print()`:
%% Cell type:code id: tags:
``` python
print(d)
print(e)
print(a, b, c)
```
%% Output
[10, 20, 30]
{'b': 20, 'a': 10}
4 3.6 abc
%% Cell type:markdown id: tags:
> _*Python 3 versus python 2*_:
>
> Print - for the print statement the brackets are compulsory for *python 3*, but are optional in python 2. So you will see plenty of code without the brackets but you should never use `print` without brackets, as this is incompatible with Python 3.
>
> Division - in python 3 all division is floating point (like in MATLAB), even if the values are integers, but in python 2 integer division works like it does in C.
---
<a class="anchor" id="Strings"></a>
## Strings
Strings can be specified using single quotes *or* double quotes - as long as they are matched.
Strings can be indexed like lists (see later).
For example:
%% Cell type:code id: tags:
``` python
s1 = "test string"
s2 = 'another test string'
print(s1, ' :: ', s2)
```
%% Output
test string :: another test string
%% Cell type:markdown id: tags:
You can also use triple quotes to capture multi-line strings. For example:
%% Cell type:code id: tags:
``` python
s3 = '''This is
a string over
multiple lines
'''
print(s3)
```
%% Output
This is
a string over
multiple lines
%% Cell type:markdown id: tags:
<a class="anchor" id="Format"></a>
### Format
More interesting strings can be created using the `format` statement, which is very useful in print statements:
%% Cell type:code id: tags:
``` python
x = 1
y = 'PyTreat'
s = 'The numerical value is {} and a name is {}'.format(x, y)
print(s)
print('A name is {} and a number is {}'.format(y, x))
```
%% Output
The numerical value is 1 and a name is PyTreat
A name is PyTreat and a number is 1
%% Cell type:markdown id: tags:
There are also other options along these lines, but this is the more modern version, although you will see plenty of the other alternatives in "old" code (to python coders this means anything written before last week).
<a class="anchor" id="String-manipulation"></a>
### String manipulation
The methods `lower()` and `upper()` are useful for strings. For example:
%% Cell type:code id: tags:
``` python
s = 'This is a Test String'
print(s.upper())
print(s.lower())
```
%% Output
THIS IS A TEST STRING
this is a test string
%% Cell type:markdown id: tags:
Another useful method is:
%% Cell type:code id: tags:
``` python
s = 'This is a Test String'
s2 = s.replace('Test', 'Better')
print(s2)
```
%% Output
This is a Better String
%% Cell type:markdown id: tags:
Strings can be concatenated just by using the `+` operator:
%% Cell type:code id: tags:
``` python
s3 = s + ' :: ' + s2
print(s3)
```
%% Output
This is a Test String :: This is a Better String
%% Cell type:markdown id: tags:
If you like regular expressions then you're in luck as these are well supported in python using the `re` module. To use this (like many other "extensions" - called _modules_ in Python - you need to `import` it). For example:
%% Cell type:code id: tags:
``` python
import re
s = 'This is a test of a Test String'
s1 = re.sub(r'a [Tt]est', "an example", s)
print(s1)
```
%% Output
This is an example of an example String
%% Cell type:markdown id: tags:
where the `r` before the quote is used to force the regular expression specification to be a `raw string`.
where the `r` before the quote is used to force the regular expression specification to be a `raw string` (see [here](https://docs.python.org/3.5/library/re.html) for more info).
For more information on matching and substitutions, look up the regular expression module on the web.
Two common and convenient string methods are `strip()` and `split()`. The first will remove any whitespace at the beginning and end of a string:
%% Cell type:code id: tags:
``` python
s2 = ' A very spacy string '
print('*' + s2 + '*')
print('*' + s2.strip() + '*')
```
%% Output
* A very spacy string *
*A very spacy string*
%% Cell type:markdown id: tags:
With `split()` we can tokenize a string (to turn it into a list of strings) like this:
%% Cell type:code id: tags:
``` python
print(s.split())
print(s2.split())
```
%% Output
['This', 'is', 'a', 'test', 'of', 'a', 'Test', 'String']
['A', 'very', 'spacy', 'string']
%% Cell type:markdown id: tags:
By default it splits at whitespace, but it can also split at a specified delimiter:
%% Cell type:code id: tags:
``` python
s4 = ' This is, as you can see , a very weirdly spaced and punctuated string ... '
print(s4.split(','))
```
%% Output
[' This is', ' as you can see ', ' a very weirdly spaced and punctuated string ... ']
%% Cell type:markdown id: tags:
There are more powerful ways of dealing with this like csv files/strings, which are covered in later practicals, but even this can get you a long way.
> Note that strings in python 3 are _unicode_ so can represent Chinese characters, etc, and is therefore very flexible. However, in general you can just be blissfully ignorant of this fact.
Strings can be converted to integer or floating-point values by using the `int()` and `float()` calls:
%% Cell type:code id: tags:
``` python
sint='23'
sfp='2.03'
print(sint + sfp)
print(int(sint) + float(sfp))
print(float(sint) + float(sfp))
```
%% Output
232.03
25.03
25.03
%% Cell type:markdown id: tags:
> Note that calling `int()` on a non-integer (e.g., on `sfp` above) will raise an error.
---
<a class="anchor" id="Tuples-and-lists"></a>
## Tuples and lists
Both tuples and lists are builtin python types and are like vectors,
but for numerical vectors and arrays it is much better to use _numpy_
arrays (or matrices), which are covered in a later tutorial.
A tuple is like a list or a vector, but with less flexibility than a full list, however anything can be stored in either a list or tuple, without any consistency being required. For example:
A tuple is like a list or a vector, but with less flexibility than a full list (tuples are immutable), however anything can be stored in either a list or tuple, without any consistency being required. Tuples are defined using round brackets and lists are defined using square brackets. For example:
%% Cell type:code id: tags:
``` python
xtuple = (3, 7.6, 'str')
xlist = [1, 'mj', -5.4]
print(xtuple)
print(xlist)
```
%% Output
(3, 7.6, 'str')
[1, 'mj', -5.4]
%% Cell type:markdown id: tags:
They can also be nested:
%% Cell type:code id: tags:
``` python
x2 = (xtuple, xlist)
x3 = [xtuple, xlist]
print('x2 is: ', x2)
print('x3 is: ', x3)
```
%% Output
x2 is: ((3, 7.6, 'str'), [1, 'mj', -5.4])
x3 is: [(3, 7.6, 'str'), [1, 'mj', -5.4]]
%% Cell type:markdown id: tags:
<a class="anchor" id="Adding-to-a-list"></a>
### Adding to a list
This is easy:
%% Cell type:code id: tags:
``` python
a = [10, 20, 30]
a = a + [70]
a += [80]
print(a)
```
%% Output
[10, 20, 30, 70, 80]
%% Cell type:markdown id: tags:
> Similar things can be done for tuples, except for the last one: that is, a += (80) as a tuple is immutable so cannot be changed like this.
<a class="anchor" id="Indexing"></a>
### Indexing
Square brackets are used to index tuples, lists, dictionaries, etc. For example:
Square brackets are used to index tuples, lists, strings, dictionaries, etc. For example:
%% Cell type:code id: tags:
``` python
d = [10, 20, 30]
print(d[1])
```
%% Output
20
%% Cell type:markdown id: tags:
> _*Pitfall:*_
> Python uses zero-based indexing, unlike MATLAB
%% Cell type:code id: tags:
``` python
a = [10, 20, 30, 40, 50, 60]
print(a[0])
print(a[2])
```
%% Output
10
30
%% Cell type:markdown id: tags:
Indices naturally run from 0 to N-1, _but_ negative numbers can be used to reference from the end (circular wrap-around).
%% Cell type:code id: tags:
``` python
print(a[-1])
print(a[-6])
```
%% Output
60
10
%% Cell type:markdown id: tags:
However, this is only true for -1 to -N. Outside of -N to N-1 will generate an `index out of range` error.
%% Cell type:code id: tags:
``` python
print(a[-7])
```
%% Output
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-149-f4cf4536701c> in <module>()
----> 1 print(a[-7])
IndexError: list index out of range
%% Cell type:code id: tags:
``` python
print(a[6])
```
%% Output
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-150-52d95fbe5286> in <module>()
----> 1 print(a[6])
IndexError: list index out of range
%% Cell type:markdown id: tags:
Length of a tuple or list is given by the `len()` function:
%% Cell type:code id: tags:
``` python
print(len(a))
```
%% Output
6
%% Cell type:markdown id: tags:
Nested lists can have nested indexing:
%% Cell type:code id: tags:
``` python
b = [[10, 20, 30], [40, 50, 60]]
print(b[0][1])
print(b[1][0])
```
%% Output
20
40
%% Cell type:markdown id: tags:
but *not* an index like b[0, 1].
but *not* an index like `b[0, 1]`. However, numpy arrays (covered in a later practical) can be indexed like `b[0, 1]` and similarly for higher dimensions.
> Note that `len` will only give the length of the top level.
> In general, numpy arrays should be preferred to nested lists when the contents are numerical.
<a class="anchor" id="Slicing"></a>
### Slicing
A range of values for the indices can be specified to extract values from a list. For example:
%% Cell type:code id: tags:
``` python
print(a[0:3])
```
%% Output
[10, 20, 30]
%% Cell type:markdown id: tags:
> _*Pitfall:*_
>
> Slicing syntax is different from MATLAB in that second number is
> exclusive (i.e., one plus final index) - this is in addition to the zero index difference.
%% Cell type:code id: tags:
``` python
a = [10, 20, 30, 40, 50, 60]
print(a[0:3]) # same as a(1:3) in MATLAB
print(a[1:3]) # same as a(2:3) in MATLAB
```
%% Output
[10, 20, 30]
[20, 30]
%% Cell type:markdown id: tags:
> _*Pitfall:*_
>
> Unlike in MATLAB, you cannot use a list as indices instead of an
> integer or a slice (although these can be done in _numpy_).
%% Cell type:code id: tags:
``` python
b = [3, 4]
print(a[b])
```
%% Output
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-155-aad7915ae3d8> in <module>()
1 b = [3, 4]
----> 2 print(a[b])
TypeError: list indices must be integers or slices, not list
%% Cell type:markdown id: tags:
In python you can leave the start and end values implicit, as it will assume these are the beginning and the end. For example:
%% Cell type:code id: tags:
``` python
print(a[:3])
print(a[1:])
print(a[:-1])
```
%% Output
[10, 20, 30]
[20, 30, 40, 50, 60]
[10, 20, 30, 40, 50]
%% Cell type:markdown id: tags:
in the last example remember that negative indices are subject to wrap around so that `a[:-1]` represents all elements up to the penultimate one.
You can also change the step size, which is specified by the third value (not the second one, as in MATLAB). For example:
%% Cell type:code id: tags:
``` python
print(a[0:4:2])
print(a[::2])
print(a[::-1])
```
%% Output
[10, 30]
[10, 30, 50]
[60, 50, 40, 30, 20, 10]
%% Cell type:markdown id: tags:
the last example is a simple way to reverse a sequence.
<a class="anchor" id="List-operations"></a>
### List operations
Multiplication can be used with lists, where multiplication implements replication.
%% Cell type:code id: tags:
``` python
d = [10, 20, 30]
print(d * 4)
```
%% Output
[10, 20, 30, 10, 20, 30, 10, 20, 30, 10, 20, 30]
%% Cell type:markdown id: tags:
There are also other operations such as:
%% Cell type:code id: tags:
``` python
d.append(40)
print(d)
d.extend([50, 60])
print(d)
d = d + [70, 80]
print(d)
d.remove(20)
print(d)
d.pop(0)
print(d)
```
%% Output
[10, 20, 30, 40]
[10, 20, 30, 40, 50, 60]
[10, 20, 30, 40, 50, 60, 70, 80]
[10, 30, 40, 50, 60, 70, 80]
[30, 40, 50, 60, 70, 80]
%% Cell type:markdown id: tags:
> Note that `d.append([50,60])` would run but instead of adding two extra elements it only adds a single element, where this element is a list of length two, making a messy list. Try it and see if this is not clear.
<a class="anchor" id="Looping"></a>
### Looping over elements in a list (or tuple)
%% Cell type:code id: tags:
``` python
d = [10, 20, 30]
for x in d:
print(x)
```
%% Output
10
20
30
%% Cell type:markdown id: tags:
> Note that the indentation within the loop is _*crucial*_. All python control blocks are delineated purely by indentation.
> Note that the indentation within the loop is _*crucial*_. All python control blocks are delineated purely by indentation. We recommend using **four spaces** and no tabs, as this is a standard practice and will help a lot when collaborating with others.
<a class="anchor" id="Getting-help"></a>
### Getting help
The function `help()` can be used to get information about any variable/object/function in python. It lists the possible operations. In `ipython` you can also just type `?<blah>` or `<blah>?` instead:
%% Cell type:code id: tags:
``` python
help(d)
```
%% Output
Help on list object:
class list(object)
| list() -> new empty list
| list(iterable) -> new list initialized from iterable's items
|
| Methods defined here:
|
| __add__(self, value, /)
| Return self+value.
|
| __contains__(self, key, /)
| Return key in self.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(...)
| x.__getitem__(y) <==> x[y]
|
| __gt__(self, value, /)
| Return self>value.
|
| __iadd__(self, value, /)
| Implement self+=value.
|
| __imul__(self, value, /)
| Implement self*=value.
|
| __init__(self, /, *args, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __mul__(self, value, /)
| Return self*value.n
|
| __ne__(self, value, /)
| Return self!=value.
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
|
| __repr__(self, /)
| Return repr(self).
|
| __reversed__(...)
| L.__reversed__() -- return a reverse iterator over the list
|
| __rmul__(self, value, /)
| Return self*value.
|
| __setitem__(self, key, value, /)
| Set self[key] to value.
|
| __sizeof__(...)
| L.__sizeof__() -- size of L in memory, in bytes
|
| append(...)
| L.append(object) -> None -- append object to end
|
| clear(...)
| L.clear() -> None -- remove all items from L
|
| copy(...)
| L.copy() -> list -- a shallow copy of L
|
| count(...)
| L.count(value) -> integer -- return number of occurrences of value
|
| extend(...)
| L.extend(iterable) -> None -- extend list by appending elements from the iterable
|
| index(...)
| L.index(value, [start, [stop]]) -> integer -- return first index of value.
| Raises ValueError if the value is not present.
|
| insert(...)
| L.insert(index, object) -- insert object before index
|
| pop(...)
| L.pop([index]) -> item -- remove and return item at index (default last).
| Raises IndexError if list is empty or index is out of range.
|
| remove(...)
| L.remove(value) -> None -- remove first occurrence of value.
| Raises ValueError if the value is not present.
|
| reverse(...)
| L.reverse() -- reverse *IN PLACE*
|
| sort(...)
| L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __hash__ = None
%% Cell type:markdown id: tags:
There is also a `dir()` function that gives a basic listing of the operations:
%% Cell type:code id: tags:
``` python
dir(d)
```
%% Output
['__add__',
'__class__',
'__contains__',
'__delattr__',
'__delitem__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__getitem__',
'__gt__',
'__hash__',
'__iadd__',
'__imul__',
'__init__',
'__iter__',
'__le__',
'__len__',
'__lt__',
'__mul__',
'__ne__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__reversed__',
'__rmul__',
'__setattr__',
'__setitem__',
'__sizeof__',
'__str__',
'__subclasshook__',
'append',
'clear',
'copy',
'count',
'extend',
'index',
'insert',
'pop',
'remove',
'reverse',
'sort']
%% Cell type:markdown id: tags:
> Note that google is often more helpful!
> Note that google is often more helpful! At least, as long as you find pages relating to the right version of python - we use python 3 for FSL, so check that what you find is appropriate for that.
---
<a class="anchor" id="Dictionaries"></a>
## Dictionaries
These store key-value pairs. For example:
%% Cell type:code id: tags:
``` python
e = {'a' : 10, 'b': 20}
print(len(e))
print(e.keys())
print(e.values())
print(e['a'])
```
%% Output
2
dict_keys(['b', 'a'])
dict_values([20, 10])
10
%% Cell type:markdown id: tags:
The keys and values can take on almost any type, even dictionaries!
Python is nothing if not flexible. However, each key must be unique
and the dictionary must be "hashable".
and [hashable](https://docs.python.org/3.5/glossary.html#term-hashable).
<a class="anchor" id="Adding-to-a-dictionary"></a>
### Adding to a dictionary
This is very easy:
%% Cell type:code id: tags:
``` python
e['c'] = 555 # just like in Biobank! ;)
print(e)
```
%% Output
{'b': 20, 'a': 10, 'c': 555}
%% Cell type:markdown id: tags:
<a class="anchor" id="Removing-elements-dictionary"></a>
### Removing elements from a dictionary
There are two main approaches - `pop` and `del`:
%% Cell type:code id: tags:
``` python
e.pop('b')
print(e)
del e['c']
print(e)
```
%% Output
{'a': 10, 'c': 555}
{'a': 10}
%% Cell type:markdown id: tags:
<a class="anchor" id="Looping-dictionary"></a>
### Looping over everything in a dictionary
Several variables can jointly work as loop variables in python, which is very convenient. For example:
%% Cell type:code id: tags:
``` python
e = {'a' : 10, 'b': 20, 'c':555}
for k, v in e.items():
print((k, v))
print((k, v))
```
%% Output
('b', 20)
('a', 10)
('c', 555)
%% Cell type:markdown id: tags:
The print statement here constructs a tuple, which is often used in python.
Another option is:
%% Cell type:code id: tags:
``` python
for k in e:
print((k, e[k]))
```
%% Output
('b', 20)
('a', 10)
('c', 555)
%% Cell type:markdown id: tags:
> Note that in both cases the order is arbitrary. The `sorted` function can be used if you want keys in a sorted order; e.g. `for k in sorted(e):` ...
>
> There are also other options if you want a dictionary with ordering.
> There are also [other options](https://docs.python.org/3.5/library/collections.html#collections.OrderedDict) if you want a dictionary with ordering.
---
<a class="anchor" id="Copying-and-references"></a>
## Copying and references
In python there are immutable types (e.g. numbers) and mutable types (e.g. lists). The main thing to know is that assignment can sometimes create separate copies and sometimes create references (as in C++). In general, the more complicated types are assigned via references. For example:
%% Cell type:code id: tags:
``` python
a = 7
b = a
a = 2348
print(b)
```
%% Output
7
%% Cell type:markdown id: tags:
As opposed to:
%% Cell type:code id: tags:
``` python
a = [7]
b = a
a[0] = 8888
print(b)
```
%% Output
[8888]
%% Cell type:markdown id: tags:
But if an operation is performed then a copy might be made:
%% Cell type:code id: tags:
``` python
a = [7]
b = a * 2
a[0] = 8888
print(b)
```
%% Output
[7, 7]
%% Cell type:markdown id: tags:
If an explicit copy is necessary then this can be made using the `list()` constructor:
%% Cell type:code id: tags:
``` python
a = [7]
b = list(a)
a[0] = 8888
print(b)
```
%% Output
[7]
%% Cell type:markdown id: tags:
There is a constructor for each type and this con be useful for converting between types:
There is a constructor for each type and this can be useful for converting between types:
%% Cell type:code id: tags:
``` python
xt = (2, 5, 7)
xl = list(xt)
print(xt)
print(xl)
```
%% Output
(2, 5, 7)
[2, 5, 7]
%% Cell type:markdown id: tags:
> _*Pitfall:*_
>
> When writing functions you need to be particularly careful about references and copies.
%% Cell type:code id: tags:
``` python
def foo1(x):
x.append(10)
x.append(10)
print('x: ', x)
def foo2(x):
x = x + [10]
x = x + [10]
print('x: ', x)
def foo3(x):
return x + [10]
print('return value: ', x + [10])
return x + [10]
a = [5]
print(a)
print('a: ', a)
foo1(a)
print(a)
print('a: ', a)
foo2(a)
print(a)
foo3(a)
print(a)
```
print('a: ', a)
b = foo3(a)
print('a: ', a)
print('b: ', b)
```
%% Output
a: [5]
x: [5, 10]
a: [5, 10]
x: [5, 10, 10]
a: [5, 10]
return value: [5, 10, 10]
a: [5, 10]
b: [5, 10, 10]
%% Cell type:markdown id: tags:
> Note that we have defined some functions here - and the syntax
> should be relatively intuitive. See <a href="#functions">below</a>
> for a bit more detail on function definitions.
---
<a class="anchor" id="Control-flow"></a>
## Control flow
<a class="anchor" id="Boolean-operators"></a>
### Boolean operators
There is a boolean type in python that can be `True` or `False` (note the capitals). Other values can also be used for True or False (e.g., 1 for True; 0 or None or [] or {} or "") although they are not considered 'equal' in the sense that the operator `==` would consider them the same.
Relevant boolean and comparison operators include: `not`, `and`, `or`, `==` and `!=`
For example:
%% Cell type:code id: tags:
``` python
a = True
print('Not a is:', not a)
print('Not 1 is:', not 1)
print('Not 0 is:', not 0)
print('Not {} is:', not {})
print('{}==0 is:', {}==0)
```
%% Output
Not a is: False
Not 1 is: False
Not 0 is: True
Not {} is: True
{}==0 is: False
%% Cell type:markdown id: tags:
There is also the `in` test for strings, lists, etc:
%% Cell type:code id: tags:
``` python
print('the' in 'a number of words')
print('of' in 'a number of words')
print(3 in [1, 2, 3, 4])
```
%% Output
False
True
True
%% Cell type:markdown id: tags:
A useful keyword is `None`, which is a bit like "null". This can be a default value for a variable and should be tested with the `is` operator rather than `==` (for technical reasons that it isn't worth going into here). For example: `a is None` or `a is not None` are the preferred tests.
<a class="anchor" id="If-statements"></a>
### If statements
The basic syntax of `if` statements is fairly standard, though don't forget that you _*must*_ indent the statements within the conditional/loop block as this is the way of delineating blocks of code in python. For example:
%% Cell type:code id: tags:
``` python
import random
a = random.uniform(-1, 1)
print(a)
if a>0:
print('Positive')
print('Positive')
elif a<0:
print('Negative')
print('Negative')
else:
print('Zero')
print('Zero')
```
%% Output
0.5890515724950383
Positive
%% Cell type:markdown id: tags:
Or more generally:
%% Cell type:code id: tags:
``` python
a = [] # just one of many examples
if not a:
print('Variable is true, or at least not empty')
print('Variable is true, or at least not empty')
```
%% Output
Variable is true, or at least not empty
%% Cell type:markdown id: tags:
This can be useful for functions where a variety of possible input types are being dealt with.
---
<a class="anchor" id="For-loops"></a>
### For loops
The `for` loop works like in bash:
%% Cell type:code id: tags:
``` python
for x in [2, 'is', 'more', 'than', 1]:
print(x)
print(x)
```
%% Output
2
is
more
than
1
%% Cell type:markdown id: tags:
where a list or any other sequence (e.g. tuple) can be used.
If you want a numerical range then use:
%% Cell type:code id: tags:
``` python
for x in range(2, 9):
print(x)
```
%% Output
2
3
4
5
6
7
8
%% Cell type:markdown id: tags:
Note that, like slicing, the maximum value is one less than the value specified. Also, `range` actually returns an object that can be iterated over but is not just a list of numbers. If you want a list of numbers then `list(range(2, 9))` will give you this.
A very nice feature of python is that multiple variables can be assigned from a tuple or list:
%% Cell type:code id: tags:
``` python
x, y = [4, 7]
print(x)
print(y)
```
%% Output
4
7
%% Cell type:markdown id: tags:
and this can be combined with a function called `zip` to make very convenient dual variable loops:
%% Cell type:code id: tags:
``` python
alist = ['Some', 'set', 'of', 'items']
blist = list(range(len(alist)))
print(list(zip(alist, blist)))
for x, y in zip(alist, blist):
print(y, x)
print(y, x)
```
%% Output
[('Some', 0), ('set', 1), ('of', 2), ('items', 3)]
0 Some
1 set
2 of
3 items
%% Cell type:markdown id: tags:
This type of loop can be used with any two lists (or similar) to iterate over them jointly.
<a class="anchor" id="While-loops"></a>
### While loops
The syntax for this is pretty standard:
%% Cell type:code id: tags:
``` python
import random
n = 0
x = 0
while n<100:
x += random.uniform(0, 1)**2 # where ** is a power operation
if x>50:
break
n += 1
x += random.uniform(0, 1)**2 # where ** is a power operation
if x>50:
break
n += 1
print(x)
```
%% Output
34.995996566662235
%% Cell type:markdown id: tags:
You can also use `continue` as in other languages.
> Note that there is no `do ... while` construct.
---
<a class="anchor" id="quick-intro"></a>
### A quick intro to conditional expressions and list comprehensions
These are more advanced bits of python but are really useful and common, so worth having a little familiarity with at this stage.
<a class="anchor" id="Conditional-expressions"></a>
#### Conditional expressions
A general expression that can be used in python is: A `if` condition `else` B
For example:
%% Cell type:code id: tags:
``` python
import random
x = random.uniform(0, 1)
y = x**2 if x<0.5 else (1 - x)**2
print(x, y)
```
%% Output
0.33573141209899227 0.11271558106998338
%% Cell type:markdown id: tags:
<a class="anchor" id="List-comprehensions"></a>
#### List comprehensions
This is a shorthand syntax for building a list like a for loop but doing it in one line, and is very popular in python. It is quite similar to mathematical set notation. For example:
%% Cell type:code id: tags:
``` python
v1 = [ x**2 for x in range(10) ]
print(v1)
v2 = [ x**2 for x in range(10) if x!=7 ]
print(v2)
```
%% Output
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
[0, 1, 4, 9, 16, 25, 36, 64, 81]
%% Cell type:markdown id: tags:
You'll find that python programmers use this kind of construction _*a lot*_.
---
<a class="anchor" id="functions"></a>
## Functions
You will find functions pretty familiar in python to start with,
although they have a few options which are really handy and different
from C++ or matlab (to be covered in a later practical). To start
with we'll look at a simple function but note a few key points:
* you _must_ indent everything inside the function (it is a code
block and indentation is the only way of determining this - just
like for the guts of a loop)
* you can return _whatever you want_ from a python function, but only
a single object - it is usual to package up multiple things in a
tuple or list, which is easily unpacked by the calling invocation:
e.g., `a, b, c = myfunc(x)`
* parameters are passed by reference (see section on <a
href="#Copying-and-references">copying and references</a>)
%% Cell type:code id: tags:
``` python
def myfunc(x, y, z=0):
r2 = x*x + y*y + z*z
r = r2**0.5
return (r, r2)
return r, r2
rad = myfunc(10, 20)
print(rad)
rad, dummy = myfunc(10, 20, 30)
print(rad)
rad, _ = myfunc(10,20,30)
print(rad)
```
%% Output
(22.360679774997898, 500)
37.416573867739416
37.416573867739416
%% Cell type:markdown id: tags:
> Note that the `_` is used as shorthand here for a dummy variable
> that you want to throw away.
>
> The return statement implicitly creates a tuple to return and is equivalent to `return (r, r2)`
One nice feature of python functions is that you can name the
arguments when you call them, rather than only doing it by position.
For example:
%% Cell type:code id: tags:
``` python
def myfunc(x, y, z=0, flag=''):
if flag=='L1':
r = abs(x) + abs(y) + abs(z)
else:
r = (x*x + y*y + z*z)**0.5
return r
if flag=='L1':
r = abs(x) + abs(y) + abs(z)
else:
r = (x*x + y*y + z*z)**0.5
return r
rA = myfunc(10, 20)
rB = myfunc(10, 20, flag='L1')
rC = myfunc(10, 20, flag='L1', z=30)
print(rA, rB, rC)
```
%% Output
22.360679774997898 30 60
%% Cell type:markdown id: tags:
You will often see python functions called with these named arguments.
You will often see python functions called with these named arguments. In fact, for functions with more than 2 or 3 variables this naming of arguments is recommended, because it clarifies what each of the arguments does for anyone reading the code.
---
<a class="anchor" id="exercise"></a>
## Exercise
Let's say you are given a single string with comma separated elements
that represent filenames and ID codes: e.g., `/vols/Data/pytreat/AAC, 165873, /vols/Data/pytreat/AAG, 170285, ...`
Write some code to do the following:
* separate out the filenames and ID codes into separate lists (ID's
should be numerical values, not strings)
should be numerical values, not strings) - you may need several steps for this
* loop over the two and generate a _string_ that could be used to
rename the directories (e.g., `mv /vols/Data/pytreat/AAC /vols/Data/pytreat/S165873`) - we will cover how to actually execute these in a later practical
* convert your dual lists into a dictionary, with ID as the key
* write a small function to determine if an ID is present in this
set of not, and also return the filename if it is
* write a for loop to create a list of all the odd-numbered IDs (you can use the `%` operator for modulus - i.e., `5 % 2` is 1)
* re-write the for loop as a list comprehension
* now generate a list of the filenames corresponding to these odd-numbered IDs
%% Cell type:code id: tags:
``` python
mstr = '/vols/Data/pytreat/AAC, 165873, /vols/Data/pytreat/AAG, 170285, /vols/Data/pytreat/AAH, 196792, /vols/Data/pytreat/AAK, 212577, /vols/Data/pytreat/AAQ, 385376, /vols/Data/pytreat/AB, 444600, /vols/Data/pytreat/AC6, 454578, /vols/Data/pytreat/V8, 501502, /vols/Data/pytreat/2YK, 667688, /vols/Data/pytreat/C3PO, 821971'
```
......
......@@ -51,7 +51,7 @@ Python has many different types and variables are dynamic and can change types (
* strings
* tuples
* lists
* dictionary
* dictionaries
N-dimensional arrays and other types are supported through common modules (e.g., numpy, scipy, scikit-learn). These will be covered in a subsequent exercise.
......@@ -146,7 +146,7 @@ s = 'This is a test of a Test String'
s1 = re.sub(r'a [Tt]est', "an example", s)
print(s1)
```
where the `r` before the quote is used to force the regular expression specification to be a `raw string`.
where the `r` before the quote is used to force the regular expression specification to be a `raw string` (see [here](https://docs.python.org/3.5/library/re.html) for more info).
For more information on matching and substitutions, look up the regular expression module on the web.
......@@ -195,7 +195,7 @@ Both tuples and lists are builtin python types and are like vectors,
but for numerical vectors and arrays it is much better to use _numpy_
arrays (or matrices), which are covered in a later tutorial.
A tuple is like a list or a vector, but with less flexibility than a full list, however anything can be stored in either a list or tuple, without any consistency being required. For example:
A tuple is like a list or a vector, but with less flexibility than a full list (tuples are immutable), however anything can be stored in either a list or tuple, without any consistency being required. Tuples are defined using round brackets and lists are defined using square brackets. For example:
```
xtuple = (3, 7.6, 'str')
xlist = [1, 'mj', -5.4]
......@@ -222,10 +222,12 @@ a += [80]
print(a)
```
> Similar things can be done for tuples, except for the last one: that is, a += (80) as a tuple is immutable so cannot be changed like this.
<a class="anchor" id="Indexing"></a>
### Indexing
Square brackets are used to index tuples, lists, dictionaries, etc. For example:
Square brackets are used to index tuples, lists, strings, dictionaries, etc. For example:
```
d = [10, 20, 30]
print(d[1])
......@@ -265,7 +267,7 @@ b = [[10, 20, 30], [40, 50, 60]]
print(b[0][1])
print(b[1][0])
```
but *not* an index like b[0, 1].
but *not* an index like `b[0, 1]`. However, numpy arrays (covered in a later practical) can be indexed like `b[0, 1]` and similarly for higher dimensions.
> Note that `len` will only give the length of the top level.
> In general, numpy arrays should be preferred to nested lists when the contents are numerical.
......@@ -299,6 +301,23 @@ b = [3, 4]
print(a[b])
```
In python you can leave the start and end values implicit, as it will assume these are the beginning and the end. For example:
```
print(a[:3])
print(a[1:])
print(a[:-1])
```
in the last example remember that negative indices are subject to wrap around so that `a[:-1]` represents all elements up to the penultimate one.
You can also change the step size, which is specified by the third value (not the second one, as in MATLAB). For example:
```
print(a[0:4:2])
print(a[::2])
print(a[::-1])
```
the last example is a simple way to reverse a sequence.
<a class="anchor" id="List-operations"></a>
### List operations
......@@ -313,12 +332,18 @@ There are also other operations such as:
```
d.append(40)
print(d)
d.extend([50, 60])
print(d)
d = d + [70, 80]
print(d)
d.remove(20)
print(d)
d.pop(0)
print(d)
```
> Note that `d.append([50,60])` would run but instead of adding two extra elements it only adds a single element, where this element is a list of length two, making a messy list. Try it and see if this is not clear.
<a class="anchor" id="Looping"></a>
### Looping over elements in a list (or tuple)
......@@ -328,7 +353,7 @@ for x in d:
print(x)
```
> Note that the indentation within the loop is _*crucial*_. All python control blocks are delineated purely by indentation.
> Note that the indentation within the loop is _*crucial*_. All python control blocks are delineated purely by indentation. We recommend using **four spaces** and no tabs, as this is a standard practice and will help a lot when collaborating with others.
<a class="anchor" id="Getting-help"></a>
### Getting help
......@@ -347,7 +372,7 @@ dir(d)
```
> Note that google is often more helpful!
> Note that google is often more helpful! At least, as long as you find pages relating to the right version of python - we use python 3 for FSL, so check that what you find is appropriate for that.
---
......@@ -365,7 +390,7 @@ print(e['a'])
The keys and values can take on almost any type, even dictionaries!
Python is nothing if not flexible. However, each key must be unique
and the dictionary must be "hashable".
and [hashable](https://docs.python.org/3.5/glossary.html#term-hashable).
<a class="anchor" id="Adding-to-a-dictionary"></a>
### Adding to a dictionary
......@@ -394,7 +419,7 @@ Several variables can jointly work as loop variables in python, which is very co
```
e = {'a' : 10, 'b': 20, 'c':555}
for k, v in e.items():
print((k, v))
print((k, v))
```
The print statement here constructs a tuple, which is often used in python.
......@@ -407,7 +432,7 @@ for k in e:
> Note that in both cases the order is arbitrary. The `sorted` function can be used if you want keys in a sorted order; e.g. `for k in sorted(e):` ...
>
> There are also other options if you want a dictionary with ordering.
> There are also [other options](https://docs.python.org/3.5/library/collections.html#collections.OrderedDict) if you want a dictionary with ordering.
---
......@@ -446,7 +471,7 @@ a[0] = 8888
print(b)
```
There is a constructor for each type and this con be useful for converting between types:
There is a constructor for each type and this can be useful for converting between types:
```
xt = (2, 5, 7)
xl = list(xt)
......@@ -460,20 +485,24 @@ print(xl)
```
def foo1(x):
x.append(10)
x.append(10)
print('x: ', x)
def foo2(x):
x = x + [10]
x = x + [10]
print('x: ', x)
def foo3(x):
return x + [10]
print('return value: ', x + [10])
return x + [10]
a = [5]
print(a)
print('a: ', a)
foo1(a)
print(a)
print('a: ', a)
foo2(a)
print(a)
foo3(a)
print(a)
print('a: ', a)
b = foo3(a)
print('a: ', a)
print('b: ', b)
```
> Note that we have defined some functions here - and the syntax
......@@ -509,6 +538,10 @@ print('of' in 'a number of words')
print(3 in [1, 2, 3, 4])
```
A useful keyword is `None`, which is a bit like "null". This can be a default value for a variable and should be tested with the `is` operator rather than `==` (for technical reasons that it isn't worth going into here). For example: `a is None` or `a is not None` are the preferred tests.
<a class="anchor" id="If-statements"></a>
### If statements
......@@ -518,18 +551,18 @@ import random
a = random.uniform(-1, 1)
print(a)
if a>0:
print('Positive')
print('Positive')
elif a<0:
print('Negative')
print('Negative')
else:
print('Zero')
print('Zero')
```
Or more generally:
```
a = [] # just one of many examples
if not a:
print('Variable is true, or at least not empty')
print('Variable is true, or at least not empty')
```
This can be useful for functions where a variety of possible input types are being dealt with.
......@@ -541,7 +574,7 @@ This can be useful for functions where a variety of possible input types are bei
The `for` loop works like in bash:
```
for x in [2, 'is', 'more', 'than', 1]:
print(x)
print(x)
```
where a list or any other sequence (e.g. tuple) can be used.
......@@ -565,7 +598,7 @@ alist = ['Some', 'set', 'of', 'items']
blist = list(range(len(alist)))
print(list(zip(alist, blist)))
for x, y in zip(alist, blist):
print(y, x)
print(y, x)
```
This type of loop can be used with any two lists (or similar) to iterate over them jointly.
......@@ -579,15 +612,17 @@ import random
n = 0
x = 0
while n<100:
x += random.uniform(0, 1)**2 # where ** is a power operation
if x>50:
break
n += 1
x += random.uniform(0, 1)**2 # where ** is a power operation
if x>50:
break
n += 1
print(x)
```
You can also use `continue` as in other languages.
> Note that there is no `do ... while` construct.
---
<a class="anchor" id="quick-intro"></a>
......@@ -645,7 +680,7 @@ with we'll look at a simple function but note a few key points:
def myfunc(x, y, z=0):
r2 = x*x + y*y + z*z
r = r2**0.5
return (r, r2)
return r, r2
rad = myfunc(10, 20)
print(rad)
......@@ -657,17 +692,19 @@ print(rad)
> Note that the `_` is used as shorthand here for a dummy variable
> that you want to throw away.
>
> The return statement implicitly creates a tuple to return and is equivalent to `return (r, r2)`
One nice feature of python functions is that you can name the
arguments when you call them, rather than only doing it by position.
For example:
```
def myfunc(x, y, z=0, flag=''):
if flag=='L1':
r = abs(x) + abs(y) + abs(z)
else:
r = (x*x + y*y + z*z)**0.5
return r
if flag=='L1':
r = abs(x) + abs(y) + abs(z)
else:
r = (x*x + y*y + z*z)**0.5
return r
rA = myfunc(10, 20)
rB = myfunc(10, 20, flag='L1')
......@@ -675,7 +712,7 @@ rC = myfunc(10, 20, flag='L1', z=30)
print(rA, rB, rC)
```
You will often see python functions called with these named arguments.
You will often see python functions called with these named arguments. In fact, for functions with more than 2 or 3 variables this naming of arguments is recommended, because it clarifies what each of the arguments does for anyone reading the code.
---
......@@ -687,7 +724,7 @@ that represent filenames and ID codes: e.g., `/vols/Data/pytreat/AAC, 165873, /v
Write some code to do the following:
* separate out the filenames and ID codes into separate lists (ID's
should be numerical values, not strings)
should be numerical values, not strings) - you may need several steps for this
* loop over the two and generate a _string_ that could be used to
rename the directories (e.g., `mv /vols/Data/pytreat/AAC /vols/Data/pytreat/S165873`) - we will cover how to actually execute these in a later practical
* convert your dual lists into a dictionary, with ID as the key
......@@ -699,6 +736,7 @@ Write some code to do the following:
```
mstr = '/vols/Data/pytreat/AAC, 165873, /vols/Data/pytreat/AAG, 170285, /vols/Data/pytreat/AAH, 196792, /vols/Data/pytreat/AAK, 212577, /vols/Data/pytreat/AAQ, 385376, /vols/Data/pytreat/AB, 444600, /vols/Data/pytreat/AC6, 454578, /vols/Data/pytreat/V8, 501502, /vols/Data/pytreat/2YK, 667688, /vols/Data/pytreat/C3PO, 821971'
```
......@@ -117,7 +117,7 @@ If the voxel size of the image is different, then extra modifications will be re
<a class="anchor" id="exercise"></a>
## Exercise
Write some code to read in a 4D fMRI image (you can find one [here] if
Write some code to read in a 4D fMRI image (you can find one [here](http://www.fmrib.ox.ac.uk/~mark/files/av.nii.gz) if
you don't have one handy), calculate the tSNR and then save the 3D result.
```
......
%% Cell type:markdown id: tags:
# Callable scripts in python
In this tutorial we will cover how to write simple stand-alone scripts in python that can be used as alternatives to bash scripts.
There are some code blocks within this webpage, but for this practical we _**strongly
recommend that you write the code in an IDE or editor**_ instead and then run the scripts from a terminal.
## Contents
* [Basic script](#basic-script)
* [Calling other executables](#calling-other-executables)
* [Command line arguments](#command-line-arguments)
* [Example script](#example-script)
* [Exercise](#exercise)
---
<a class="anchor" id="basic-script"></a>
## Basic script
The first line of a python script is usually:
%% Cell type:code id: tags:
```
``` python
#!/usr/bin/env python
```
%% Cell type:markdown id: tags:
which invokes whichever version of python can be found by `/usr/bin/env` since python can be located in many different places.
For FSL scripts we use an alternative, to ensure that we pick up the version of python (and associated packages) that we ship with FSL. To do this we use the line:
%% Cell type:code id: tags:
```
``` python
#!/usr/bin/env fslpython
```
%% Cell type:markdown id: tags:
After this line the rest of the file just uses regular python syntax, as in the other tutorials. Make sure you make the file executable - just like a bash script.
<a class="anchor" id="calling-other-executables"></a>
## Calling other executables
The most essential call that you need to use to replicate the way a bash script calls executables is `subprocess.run()`. A simple call looks like this:
%% Cell type:code id: tags:
```
``` python
import subprocess as sp
sp.run(['ls', '-la'])
```
%% Cell type:markdown id: tags:
To suppress the output do this:
%% Cell type:code id: tags:
```
``` python
spobj = sp.run(['ls'], stdout = sp.PIPE)
```
%% Cell type:markdown id: tags:
To store the output do this:
%% Cell type:code id: tags:
```
``` python
spobj = sp.run('ls -la'.split(), stdout = sp.PIPE)
sout = spobj.stdout.decode('utf-8')
print(sout)
```
%% Cell type:markdown id: tags:
> Note that the `decode` call in the middle line converts the string from a byte string to a normal string. In Python 3 there is a distinction between strings (sequences of characters, possibly using multiple bytes to store each character) and bytes (sequences of bytes). The world has moved on from ASCII, so in this day and age, this distinction is absolutely necessary, and Python does a fairly good job of it.
If the output is numerical then this can be extracted like this:
%% Cell type:code id: tags:
```
``` python
import os
fsldir = os.getenv('FSLDIR')
spobj = sp.run([fsldir+'/bin/fslstats', fsldir+'/data/standard/MNI152_T1_1mm_brain', '-V'], stdout = sp.PIPE)
sout = spobj.stdout.decode('utf-8')
vol_vox = float(sout.split()[0])
vol_mm = float(sout.split()[1])
print('Volumes are: ', vol_vox, ' in voxels and ', vol_mm, ' in mm')
```
%% Cell type:markdown id: tags:
An alternative way to run a set of commands would be like this:
%% Cell type:code id: tags:
```
``` python
commands = """
{fsldir}/bin/fslmaths {t1} -bin {t1_mask}
{fsldir}/bin/fslmaths {t2} -mas {t1_mask} {t2_masked}
"""
fsldirpath = os.getenv('FSLDIR')
commands = commands.format(t1 = 't1.nii.gz', t1_mask = 't1_mask', t2 = 't2', t2_masked = 't2_masked', fsldir = fsldirpath)
sout=[]
for cmd in commands.split('\n'):
if cmd: # avoids empty strings getting passed to sp.run()
print('Running command: ', cmd)
spobj = sp.run(cmd.split(), stdout = sp.PIPE)
sout.append(spobj.stdout.decode('utf-8'))
```
%% Cell type:markdown id: tags:
<a class="anchor" id="command-line-arguments"></a>
## Command line arguments
The simplest way of dealing with command line arguments is use the module `sys`, which gives access to an `argv` list:
%% Cell type:code id: tags:
```
``` python
import sys
print(len(sys.argv))
print(sys.argv[0])
```
%% Cell type:markdown id: tags:
For more sophisticated argument parsing you can use `argparse` - good documentation and examples of this can be found on the web.
---
<a class="anchor" id="example-script"></a>
## Example script
Here is a simple bash script (it masks an image and calculates volumes - just as a random example). DO NOT execute the code blocks here within the notebook/webpage:
%% Cell type:code id: tags:
```
``` python
#!/bin/bash
if [ $# -lt 2 ] ; then
echo "Usage: $0 <input image> <output image>"
exit 1
fi
infile=$1
outfile=$2
# mask input image with MNI
$FSLDIR/bin/fslmaths $infile -mas $FSLDIR/data/standard/MNI152_T1_1mm_brain $outfile
# calculate volumes of masked image
vv=`$FSLDIR/bin/fslstats $outfile -V`
vol_vox=`echo $vv | awk '{ print $1 }'`
vol_mm=`echo $vv | awk '{ print $2 }'`
echo "Volumes are: $vol_vox in voxels and $vol_mm in mm"
```
%% Cell type:markdown id: tags:
And an alternative in python:
%% Cell type:code id: tags:
```
``` python
#!/usr/bin/env fslpython
import os, sys
import subprocess as sp
fsldir=os.getenv('FSLDIR')
if len(sys.argv)<2:
print('Usage: ', sys.argv[0], ' <input image> <output image>')
sys.exit(1)
infile = sys.argv[1]
outfile = sys.argv[2]
# mask input image with MNI
spobj = sp.run([fsldir+'/bin/fslmaths', infile, '-mas', fsldir+'/data/standard/MNI152_T1_1mm_brain', outfile], stdout = sp.PIPE)
# calculate volumes of masked image
spobj = sp.run([fsldir+'/bin/fslstats', outfile, '-V'], stdout = sp.PIPE)
sout = spobj.stdout.decode('utf-8')
vol_vox = float(sout.split()[0])
vol_mm = float(sout.split()[1])
print('Volumes are: ', vol_vox, ' in voxels and ', vol_mm, ' in mm')
```
%% Cell type:markdown id: tags:
---
<a class="anchor" id="exercise"></a>
## Exercise
Write a simple version of fslstats that is able to calculate either a
mean or a _sum_ (and hence can do something that fslstats cannot!)
%% Cell type:code id: tags:
```
``` python
# Don't write anything here - do it in a standalone script!
```
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment