Skip to content
Snippets Groups Projects
Commit fdbc76c5 authored by Mihai Lefter's avatar Mihai Lefter
Browse files

Add hands on exercises for the 3rd introduction session.

parent d9cde0db
No related branches found
No related tags found
No related merge requests found
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
<span style="font-size: 200%">Introduction to Python (3)</span> <span style="font-size: 200%">Introduction to Python (3)</span>
=== ===
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Functions Functions
=== ===
A _function_ is a named sequence of statements that performs some piece of work. A _function_ is a named sequence of statements that performs some piece of work.
Later on that function can be called by using its name. Later on that function can be called by using its name.
Defining a function Defining a function
--- ---
A function definition includes its _name_, _arguments_ and _body_. A function definition includes its _name_, _arguments_ and _body_.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
def add_two(number): def add_two(number):
return number + 2 return number + 2
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
for i in range(5): for i in range(5):
print add_two(i) print add_two(i)
``` ```
%% Output %% Output
2 2
3 3
4 4
5 5
6 6
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Functions Functions
=== ===
Keyword arguments Keyword arguments
--- ---
Besides regular arguments, functions can have keyword arguments. Besides regular arguments, functions can have keyword arguments.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
def add_some_other_number(number, other_number=12): def add_some_other_number(number, other_number=12):
return number + other_number return number + other_number
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
add_some_other_number(2, 6) add_some_other_number(2, 6)
``` ```
%% Output %% Output
8 8
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
add_some_other_number(3, other_number=4) add_some_other_number(3, other_number=4)
``` ```
%% Output %% Output
7 7
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
add_some_other_number(5) add_some_other_number(5)
``` ```
%% Output %% Output
17 17
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Functions Functions
=== ===
Docstrings Docstrings
--- ---
Like many other definitions, functions can have docstrings. Like many other definitions, functions can have docstrings.
* Docstrings are regular string values which you start the definition body with. * Docstrings are regular string values which you start the definition body with.
* You can access an object's docstring using `help`. * You can access an object's docstring using `help`.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
def factorial(n): def factorial(n):
"""Compute factorial of n in the obious way.""" """Compute factorial of n in the obious way."""
if n == 0: if n == 0:
return 1 return 1
else: else:
return factorial(n - 1) * n return factorial(n - 1) * n
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
help(factorial) help(factorial)
``` ```
%% Output %% Output
Help on function factorial in module __main__: Help on function factorial in module __main__:
factorial(n) factorial(n)
Compute factorial of n in the obious way. Compute factorial of n in the obious way.
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Functions Functions
=== ===
Functions are values Functions are values
--- ---
We can pass functions around just like other values, and call them. We can pass functions around just like other values, and call them.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
functions = [add_two, add_some_other_number] functions = [add_two, add_some_other_number]
for function in functions: for function in functions:
print function(7) print function(7)
``` ```
%% Output %% Output
9 9
19 19
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Simple anonymous functions can be created with `lambda`. Simple anonymous functions can be created with `lambda`.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
functions.append(lambda x: x * 7) functions.append(lambda x: x * 7)
for function in functions: for function in functions:
print function(4) print function(4)
``` ```
%% Output %% Output
6 6
16 16
28 28
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Functions Functions
=== ===
Higher-order functions Higher-order functions
--- ---
A function that takes a function as argument is a higher-order function. A function that takes a function as argument is a higher-order function.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
help(map) help(map)
``` ```
%% Output %% Output
Help on built-in function map in module __builtin__: Help on built-in function map in module __builtin__:
map(...) map(...)
map(function, sequence[, sequence, ...]) -> list map(function, sequence[, sequence, ...]) -> list
Return a list of the results of applying the function to the items of Return a list of the results of applying the function to the items of
the argument sequence(s). If more than one sequence is given, the the argument sequence(s). If more than one sequence is given, the
function is called with an argument list consisting of the corresponding function is called with an argument list consisting of the corresponding
item of each sequence, substituting None for missing values when not all item of each sequence, substituting None for missing values when not all
sequences have the same length. If the function is None, return a list of sequences have the same length. If the function is None, return a list of
the items of the sequence (or a list of tuples if more than one sequence). the items of the sequence (or a list of tuples if more than one sequence).
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
map(add_two, [1, 2, 3, 4]) map(add_two, [1, 2, 3, 4])
``` ```
%% Output %% Output
[3, 4, 5, 6] [3, 4, 5, 6]
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
$\S$ Exercise: k-mer counting (1/2) <div class="alert alert-success">
=== <h1>Hands on!</h1>
Remember the previous exercise of finding (unique) substrings of length 3.
* Make a function from your implementation.
* Have `k` as an argument to the function.
* Test the function on several input strings.
**Note:** Editing multi-line statements in the console can be frustrating. You can try the QT console (`ipython qtconsole`) or edit your function in an editor with `%edit`:
def my_function(arg):
print arg * 4
%edit my_function
%% Cell type:markdown id: tags: <ol>
<li>Write a Python function that returns the maximum of two numbers.</li>
$\S$ Exercise: k-mer counting (2/2) <li>Write a Python function that returns the maximum of three numbers. Try to reuse the first maximum of two numbers function.</li>
=== <li>Write a Python function that accepts a string as parameter. Next, it calculates and prints the number of upper case letters and lower case letters. Make us of the `isupper` and `islower` built in methods.</li>
</ol>
Modify your function to use a dictionary with substring counts. </div>
* Use the substrings as dictionary keys.
* Use the counts as dictionary values.
* Have the function return the dictionary.
* Add a docstring to the function.
* Use the function to print k-mer counts for some strings.
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Comprehensions Comprehensions
=== ===
List comprehensions List comprehensions
--- ---
Similar to mathematical set notation (e.g., $\{ x ~|~ x \in \mathbf R \land x > 0\}$), we can create lists. Similar to mathematical set notation (e.g., $\{ x ~|~ x \in \mathbf R \land x > 0\}$), we can create lists.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
[(x, x * x) for x in range(10) if x % 2] [(x, x * x) for x in range(10) if x % 2]
``` ```
%% Output %% Output
[(1, 1), (3, 9), (5, 25), (7, 49), (9, 81)] [(1, 1), (3, 9), (5, 25), (7, 49), (9, 81)]
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
We can do the same thing using `map` and `filter`, but list comprehensions are often more readable. We can do the same thing using `map` and `filter`, but list comprehensions are often more readable.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
map(lambda x: (x, x * x), filter(lambda x: x %2, range(10))) map(lambda x: (x, x * x), filter(lambda x: x %2, range(10)))
``` ```
%% Output %% Output
[(1, 1), (3, 9), (5, 25), (7, 49), (9, 81)] [(1, 1), (3, 9), (5, 25), (7, 49), (9, 81)]
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Comprehensions Comprehensions
=== ===
Set and dictionary comprehensions Set and dictionary comprehensions
--- ---
Similar notation can be used for (non-empty) sets. Similar notation can be used for (non-empty) sets.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
{c for c in 'LUMC-standard' if 'a' <= c <= 'z'} {c for c in 'LUMC-standard' if 'a' <= c <= 'z'}
``` ```
%% Output %% Output
{'a', 'd', 'n', 'r', 's', 't'} {'a', 'd', 'n', 'r', 's', 't'}
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
And dictionaries. And dictionaries.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
colors = ['red', 'white', 'blue', 'orange'] colors = ['red', 'white', 'blue', 'orange']
{c: len(c) for c in colors} {c: len(c) for c in colors}
``` ```
%% Output %% Output
{'blue': 4, 'orange': 6, 'red': 3, 'white': 5} {'blue': 4, 'orange': 6, 'red': 3, 'white': 5}
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Everything is an object Everything is an object
=== ===
* Objects have properties and methods. * Objects have properties and methods.
* Explore them using `dir(o)`, or by typing `o.<tab>` in the IPython interpreter. * Explore them using `dir(o)`, or by typing `o.<tab>` in the IPython interpreter.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
dir('abc')[-5:] dir('abc')[-5:]
``` ```
%% Output %% Output
['swapcase', 'title', 'translate', 'upper', 'zfill'] ['swapcase', 'title', 'translate', 'upper', 'zfill']
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
help('abc'.upper) help('abc'.upper)
``` ```
%% Output %% Output
Help on built-in function upper: Help on built-in function upper:
upper(...) upper(...)
S.upper() -> string S.upper() -> string
Return a copy of the string S converted to uppercase. Return a copy of the string S converted to uppercase.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
'abc'.upper() 'abc'.upper()
``` ```
%% Output %% Output
'ABC' 'ABC'
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Code in files Code in files
=== ===
Running code from a file Running code from a file
--- ---
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
cat examples/fsquare.py cat examples/fsquare.py
``` ```
%% Output %% Output
d = {} d = {}
for i in range(10): for i in range(10):
d[i] = i ** 2 d[i] = i ** 2
for i in d: for i in d:
print "{0} is the square of {1}.".format(d[i], i) print "{0} is the square of {1}.".format(d[i], i)
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
%%sh %%sh
python examples/fsquare.py python examples/fsquare.py
``` ```
%% Output %% Output
0 is the square of 0. 0 is the square of 0.
1 is the square of 1. 1 is the square of 1.
4 is the square of 2. 4 is the square of 2.
9 is the square of 3. 9 is the square of 3.
16 is the square of 4. 16 is the square of 4.
25 is the square of 5. 25 is the square of 5.
36 is the square of 6. 36 is the square of 6.
49 is the square of 7. 49 is the square of 7.
64 is the square of 8. 64 is the square of 8.
81 is the square of 9. 81 is the square of 9.
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Code in files Code in files
=== ===
Working with files in IPython Working with files in IPython
--- ---
The `%run` magic runs the code from a file directly in IPython: The `%run` magic runs the code from a file directly in IPython:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
%run examples/fsquare.py %run examples/fsquare.py
``` ```
%% Output %% Output
0 is the square of 0. 0 is the square of 0.
1 is the square of 1. 1 is the square of 1.
4 is the square of 2. 4 is the square of 2.
9 is the square of 3. 9 is the square of 3.
16 is the square of 4. 16 is the square of 4.
25 is the square of 5. 25 is the square of 5.
36 is the square of 6. 36 is the square of 6.
49 is the square of 7. 49 is the square of 7.
64 is the square of 8. 64 is the square of 8.
81 is the square of 9. 81 is the square of 9.
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
You can edit and run a file with `%edit`. You can edit and run a file with `%edit`.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
%edit examples/fsquare.py %edit examples/fsquare.py
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Code in files Code in files
=== ===
Saving your IPython session history to a file Saving your IPython session history to a file
--- ---
Give the `%save` magic a name and a range of input lines and it will save them to a `.py` file with that name: Give the `%save` magic a name and a range of input lines and it will save them to a `.py` file with that name:
In [4]: %save my_session 1-3 In [4]: %save my_session 1-3
The following commands were written to file `my_session.py`: The following commands were written to file `my_session.py`:
a = 4 a = 4
a += 3 a += 3
b = a b = a
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
$\S$ Exercise: Running code from a file
===
* Save your k-mer counting code to a file `kmer_counting.py`.
* Include some code using it on an example string and printing the results.
* Run the code from the command line.
%% Cell type:markdown id: tags:
Further reading Further reading
=== ===
* [The Python Tutorial](http://docs.python.org/2/tutorial/index.html) * [The Python Tutorial](http://docs.python.org/2/tutorial/index.html)
<br> <br>
From the official Python documentation. From the official Python documentation.
* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) * [Learn Python The Hard Way](http://learnpythonthehardway.org/book/)
<br> <br>
Book on learning Python by exercises, online available for free. Book on learning Python by exercises, online available for free.
* [The Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) * [The Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/)
<br> <br>
This opinionated guide exists to provide both novice and expert Python developers a best-practice handbook to the installation, configuration, and usage of Python on a daily basis. This opinionated guide exists to provide both novice and expert Python developers a best-practice handbook to the installation, configuration, and usage of Python on a daily basis.
* [A Primer on Scientific Programming with Python](http://codingcat.com/knjige/python/A%20Primer%20on%20Scientific%20Programming%20with%20Python.pdf) * [A Primer on Scientific Programming with Python](http://codingcat.com/knjige/python/A%20Primer%20on%20Scientific%20Programming%20with%20Python.pdf)
<br> <br>
Complete PDF version of the book. The aim of this book is to teach computer programming using examples from mathematics and the natural sciences. Complete PDF version of the book. The aim of this book is to teach computer programming using examples from mathematics and the natural sciences.
* [Python Module of the Week](http://pymotw.com/) * [Python Module of the Week](http://pymotw.com/)
<br> <br>
Series of articles providing a tour of the Python standard library through short examples. Series of articles providing a tour of the Python standard library through short examples.
%% Cell type:markdown id: tags:
Homework assignment
===
https://classroom.github.com/a/QU2iPYKn
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
from IPython.display import HTML from IPython.display import HTML
def css_styling(): def css_styling():
styles = open('styles/custom.css', 'r').read() styles = open('styles/custom.css', 'r').read()
return HTML('<style>' + styles + '</style>') return HTML('<style>' + styles + '</style>')
css_styling() css_styling()
``` ```
%% Output %% Output
<IPython.core.display.HTML at 0x2e0ea50> <IPython.core.display.HTML at 0x2e0ea50>
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Acknowledgements Acknowledgements
======== ========
Martijn Vermaat Martijn Vermaat
[Jeroen Laros](mailto:j.f.j.laros@lumc.nl) [Jeroen Laros](mailto:j.f.j.laros@lumc.nl)
Based on Based on
--------- ---------
[Python Scientific Lecture Notes](http://scipy-lectures.github.io/) [Python Scientific Lecture Notes](http://scipy-lectures.github.io/)
License License
-------- --------
[Creative Commons Attribution 3.0 License (CC-by)](http://creativecommons.org/licenses/by/3.0) [Creative Commons Attribution 3.0 License (CC-by)](http://creativecommons.org/licenses/by/3.0)
......
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