-
Mark Jenkinson authoredMark Jenkinson authored
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
- Control flow
- Functions
- Exercise
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
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.
a = 4
b = 3.6
c = 'abc'
d = [10, 20, 30]
e = {'a' : 10, 'b': 20}
print(a)
Any variable or combination of variables can be printed using the function print()
:
print(d)
print(e)
print(a, b, c)
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
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.
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:
s1 = "test string"
s2 = 'another test string'
print(s1, ' :: ', s2)
You can also use triple quotes to capture multi-line strings. For example:
s3 = '''This is
a string over
multiple lines
'''
print(s3)
Format
More interesting strings can be created using the format
statement, which is very useful in print statements:
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))
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).
String manipulation
The methods lower()
and upper()
are useful for strings. For example:
s = 'This is a Test String'
print(s.upper())
print(s.lower())
Another useful method is:
s = 'This is a Test String'
s2 = s.replace('Test', 'Better')
print(s2)
Strings can be concatenated just by using the +
operator:
s3 = s + ' :: ' + s2
print(s3)
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:
import re
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
.
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:
s2 = ' A very spacy string '
print('*' + s2 + '*')
print('*' + s2.strip() + '*')
With split()
we can tokenize a string (to turn it into a list of strings) like this:
print(s.split())
print(s2.split())
By default it splits at whitespace, but it can also split at a specified delimiter:
s4 = ' This is, as you can see , a very weirdly spaced and punctuated string ... '
print(s4.split(','))
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:
sint='23'
sfp='2.03'
print(sint + sfp)
print(int(sint) + float(sfp))
print(float(sint) + float(sfp))
Note that calling
int()
on a non-integer (e.g., onsfp
above) will raise an error.
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:
xtuple = (3, 7.6, 'str')
xlist = [1, 'mj', -5.4]
print(xtuple)
print(xlist)
They can also be nested:
x2 = (xtuple, xlist)
x3 = [xtuple, xlist]
print('x2 is: ', x2)
print('x3 is: ', x3)
Adding to a list
This is easy:
a = [10, 20, 30]
a = a + [70]
a += [80]
print(a)
Indexing
Square brackets are used to index tuples, lists, dictionaries, etc. For example:
d = [10, 20, 30]
print(d[1])
Pitfall: Python uses zero-based indexing, unlike MATLAB
a = [10, 20, 30, 40, 50, 60]
print(a[0])
print(a[2])
Indices naturally run from 0 to N-1, but negative numbers can be used to reference from the end (circular wrap-around).
print(a[-1])
print(a[-6])
However, this is only true for -1 to -N. Outside of -N to N-1 will generate an index out of range
error.
print(a[-7])
print(a[6])
Length of a tuple or list is given by the len()
function:
print(len(a))
Nested lists can have nested indexing:
b = [[10, 20, 30], [40, 50, 60]]
print(b[0][1])
print(b[1][0])
but not an index like b[0, 1].
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.
Slicing
A range of values for the indices can be specified to extract values from a list. For example:
print(a[0:3])
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.
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
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).
b = [3, 4]
print(a[b])
List operations
Multiplication can be used with lists, where multiplication implements replication.
d = [10, 20, 30]
print(d * 4)
There are also other operations such as:
d.append(40)
print(d)
d.remove(20)
print(d)
d.pop(0)
print(d)
Looping over elements in a list (or tuple)
d = [10, 20, 30]
for x in d:
print(x)
Note that the indentation within the loop is crucial. All python control blocks are delineated purely by indentation.
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:
help(d)
There is also a dir()
function that gives a basic listing of the operations:
dir(d)
Note that google is often more helpful!
Dictionaries
These store key-value pairs. For example:
e = {'a' : 10, 'b': 20}
print(len(e))
print(e.keys())
print(e.values())
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".
Adding to a dictionary
This is very easy:
e['c'] = 555 # just like in Biobank! ;)
print(e)