Skip to content

Instantly share code, notes, and snippets.

@NelleV
Created April 20, 2013 07:29
Show Gist options
  • Save NelleV/5425126 to your computer and use it in GitHub Desktop.
Save NelleV/5425126 to your computer and use it in GitHub Desktop.
Agramfort-2
{
"metadata": {
"name": "Lecture-1-Introduction-to-Python-Programming"
},
"nbformat": 3,
"nbformat_minor": 0,
"worksheets": [
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Introduction to the Python programming language\n",
"\n",
"A. Gramfort ([email protected]) http://alexandre.gramfort.net\n",
"\n",
"based on the work of J.R. Johansson ([email protected]) http://dml.riken.jp/~rob/"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Python program files\n",
"\n",
"* Python code is usually stored in text files with the file ending \"`.py`\":\n",
"\n",
" myprogram.py\n",
"\n",
"* Every line in a Python program file is assumed to be a Python statement, or part thereof. \n",
"\n",
" * The only exception is comment lines, which start with the character `#` (optionally preceded by an arbitrary number of white-space characters, i.e., tabs or spaces). Comment lines are usually ignored by the Python interpreter.\n",
"\n",
"\n",
"* To run our Python program from the command line we use:\n",
"\n",
" $ python myprogram.py\n",
"\n",
"* On UNIX systems it is common to define the path to the interpreter on the first line of the program (note that this is a comment line as far as the Python interpreter is concerned):\n",
"\n",
" #!/usr/bin/env python\n",
"\n",
" If we do, and if we additionally set the file script to be executable, we can run the program like this:\n",
"\n",
" $ ./myprogram.py\n",
"\n",
"#### Example:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"ls scripts/hello-world*.py"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"scripts/hello-world-in-french.py scripts/hello-world.py\r\n"
]
}
],
"prompt_number": 3
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"cat scripts/hello-world.py"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"#!/usr/bin/env python\r\n",
"\r\n",
"print(\"Hello world!\")\r\n"
]
}
],
"prompt_number": 6
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"!python scripts/hello-world.py"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"Hello world!\r\n"
]
}
],
"prompt_number": 7
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Character encoding\n",
"\n",
"The standard character encoding is ASCII, but we can use any other encoding, for example UTF-8. To specify that UTF-8 is used we include the special line\n",
"\n",
" # -*- coding: UTF-8 -*-\n",
"\n",
"at the top of the file."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"cat scripts/hello-world-in-french.py"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"#!/usr/bin/env python\r\n",
"# -*- coding: UTF-8 -*-\r\n",
"\r\n",
"print(\"Bonjour \u00e0 tout le monde!\")\r\n"
]
}
],
"prompt_number": 11
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"!python scripts/hello-world-in-french.py"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"Bonjour \u00e0 tout le monde!\r\n"
]
}
],
"prompt_number": 12
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Other than these two *optional* lines in the beginning of a python code file, no additional code is required for for initializing a program. "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## IPython notebooks\n",
"\n",
"This document is not a .py file but an IPython notebook stored as a file in the [JSON](http://en.wikipedia.org/wiki/JSON) format."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Playing with numbers\n",
"--------------------"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"1 + 1"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "pyout",
"prompt_number": 13,
"text": [
"2"
]
}
],
"prompt_number": 13
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"6 * 7"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "pyout",
"prompt_number": 14,
"text": [
"42"
]
}
],
"prompt_number": 14
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"a = 4 # assign value 4 to variable a"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 16
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"print a"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"4\n"
]
}
],
"prompt_number": 18
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"type(a) # what is the type of a?"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "pyout",
"prompt_number": 17,
"text": [
"int"
]
}
],
"prompt_number": 17
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Variable names in Python can contain alphanumerical characters `a-z`, `A-Z`, `0-9` and some special characters such as `_`. Normal variable names must start with a letter. \n",
"\n",
"By convension, variable names start with a lower-case letter, and Class names start with a capital letter. \n",
"\n",
"In addition, there are a number of Python keywords that cannot be used as variable names. These keywords are:\n",
"\n",
" and, as, assert, break, class, continue, def, del, elif, else, except, \n",
" exec, finally, for, from, global, if, import, in, is, lambda, not, or,\n",
" pass, print, raise, return, try, while, with, yield\n",
"\n",
"Note: Be aware of the keyword **lambda**, which could easily be a natural variable name in a scientific program. But being a keyword, it cannot be used as a variable name."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**NOTE**"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"int a = 1; # in C"
],
"language": "python",
"metadata": {},
"outputs": [
{
"ename": "SyntaxError",
"evalue": "invalid syntax (<ipython-input-19-232418b2343a>, line 1)",
"output_type": "pyerr",
"traceback": [
"\u001b[0;36m File \u001b[0;32m\"<ipython-input-19-232418b2343a>\"\u001b[0;36m, line \u001b[0;32m1\u001b[0m\n\u001b[0;31m int a = 1; # in C\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m invalid syntax\n"
]
}
],
"prompt_number": 19
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"c = 2.1\n",
"print type(c)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"<type 'float'>\n"
]
}
],
"prompt_number": 20
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"a = 1.5 + 0.5j\n",
"print a.real\n",
"print a.imag\n",
"print type(a)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"1.5\n",
"0.5\n",
"<type 'complex'>\n"
]
}
],
"prompt_number": 21
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"print c"
],
"language": "python",
"metadata": {},
"outputs": [
{
"ename": "NameError",
"evalue": "name 'c' is not defined",
"output_type": "pyerr",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m\n\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-12-8e698a6f794d>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0;32mprint\u001b[0m \u001b[0mc\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[0;31mNameError\u001b[0m: name 'c' is not defined"
]
}
],
"prompt_number": 12
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"3 < 4"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "pyout",
"prompt_number": 22,
"text": [
"True"
]
}
],
"prompt_number": 22
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"test = (3 > 4)"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 23
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"type(test)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "pyout",
"prompt_number": 24,
"text": [
"bool"
]
}
],
"prompt_number": 24
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"7 * 3."
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "pyout",
"prompt_number": 25,
"text": [
"21.0"
]
}
],
"prompt_number": 25
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"2**10"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "pyout",
"prompt_number": 26,
"text": [
"1024"
]
}
],
"prompt_number": 26
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"8 % 3"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "pyout",
"prompt_number": 27,
"text": [
"2"
]
}
],
"prompt_number": 27
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**WARNING**"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"1/2 # !!!!!"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "pyout",
"prompt_number": 33,
"text": [
"0"
]
}
],
"prompt_number": 33
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"1/2. # OK"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "pyout",
"prompt_number": 34,
"text": [
"0.5"
]
}
],
"prompt_number": 34
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"1 / float(2) # OK too"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "pyout",
"prompt_number": 35,
"text": [
"0.5"
]
}
],
"prompt_number": 35
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"cos(2)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"ename": "NameError",
"evalue": "name 'cos' is not defined",
"output_type": "pyerr",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m\n\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-1-43abd96808db>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mcos\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m2\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[0;31mNameError\u001b[0m: name 'cos' is not defined"
]
}
],
"prompt_number": 1
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Modules\n",
"\n",
"Most of the functionality in Python is provided by *modules*.\n",
"\n",
"The Python Standard Library is a large collection of modules to access the operating system, do file I/O, string management, network communication, and much more.\n",
"\n",
"### References\n",
" \n",
" * The Python Language Reference: http://docs.python.org/2/reference/index.html\n",
" * The Python Standard Library: http://docs.python.org/2/library/\n",
"\n",
"To use a module in a python program it first has to be imported. A module can be imported using the `import` statement. For example, to import the module `math`, which contains many standard mathematical functions, we can do:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"import math"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 6
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This includes the whole module and makes it available for use later in the program. For example, we can do:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"import math\n",
"\n",
"print math.cos(2 * math.pi)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"1.0\n"
]
}
],
"prompt_number": 3
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Alternatively, we can chose to import all symbols (functions and variables) in a module to the current namespace (so that we don't need to use the prefix \"`math.`\" every time we use something from the `math` module:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"from math import cos, pi\n",
"\n",
"x = cos(2 * pi)\n",
"\n",
"print x"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"1.0\n"
]
}
],
"prompt_number": 5
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This is pattern can be very convenient, but in large programs that include many modules it is often a good idea to keep the symbols from each module in their own namespaces, by using the `import math` pattern. This would elminate potentially confusing problems with name space collisions.\n",
"\n",
"As a third alternative, we can chose to import only a few selected symbols from a module by explicitly listing which ones we want to import instead of using the wildcard character `*`:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"from math import cos, pi\n",
"\n",
"x = cos(2 * pi)\n",
"\n",
"print x"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"1.0\n"
]
}
],
"prompt_number": 9
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Looking at what a module contains, and its documentation\n",
"\n",
"Once a module is imported, we can list the symbols it provides using the `dir` function:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"import math\n",
"\n",
"print dir(math)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"['__doc__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'hypot', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']\n"
]
}
],
"prompt_number": 10
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"And using the funciton **`help`** we can get a description of each function (most functions have docstrings). "
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"help(math.log)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"Help on built-in function log in module math:\n",
"\n",
"log(...)\n",
" log(x[, base])\n",
" \n",
" Return the logarithm of x to the given base.\n",
" If the base not specified, returns the natural logarithm (base e) of x.\n",
"\n"
]
}
],
"prompt_number": 6
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### or with IPython use **\"?\"**"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"math.log?"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 10
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"math.log(10, 2)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "pyout",
"prompt_number": 11,
"text": [
"3.3219280948873626"
]
}
],
"prompt_number": 11
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"math.ceil(2.7) # round to the next integer"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "pyout",
"prompt_number": 107,
"text": [
"3.0"
]
}
],
"prompt_number": 107
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can also use the `help` function directly on modules: Try\n",
"\n",
" help(math) \n",
"\n",
"Some very useful modules form the Python standard library are `os`, `sys`, `math`, `shutil`, `re`, `subprocess`, `multiprocessing`, `threading`. \n",
"\n",
"A complete lists of standard modules for Python 2 and Python 3 are available at http://docs.python.org/2/library/ and http://docs.python.org/3/library/, respectively."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## EXCERCISE : Calculate the next power of 2 of a number n"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"n = 12345\n",
"# new_pow2 = "
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 108
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### More on Types\n",
"\n",
"Test if variables are of certain types:"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can also use the `isinstance` method for testing types of variables:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"x = 1.1\n",
"isinstance(x, float)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "pyout",
"prompt_number": 14,
"text": [
"True"
]
}
],
"prompt_number": 14
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Type casting"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"x = 1\n",
"print x, type(x)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"1 <type 'int'>\n"
]
}
],
"prompt_number": 18
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"y = float(x) # cast as float\n",
"print y, type(y)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"1.0 <type 'float'>\n"
]
}
],
"prompt_number": 20
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Complex variables **cannot be cast** to floats or integers:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"print float(z)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"ename": "TypeError",
"evalue": "can't convert complex to float",
"output_type": "pyerr",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m\n\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-24-3a73631a07d9>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0;32mprint\u001b[0m \u001b[0mfloat\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mz\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[0;31mTypeError\u001b[0m: can't convert complex to float"
]
}
],
"prompt_number": 24
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Operators and comparisons\n",
"\n",
"Most operators and comparisons in Python work as one would expect:\n",
"\n",
"* Arithmetic operators `+`, `-`, `*`, `/`, `//` (integer division), '**' power"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"print 1*2, 1+1, 1*3, 3//2, 2**2"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"2 2 3 1 4\n"
]
}
],
"prompt_number": 25
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"True and False"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "pyout",
"prompt_number": 26,
"text": [
"False"
]
}
],
"prompt_number": 26
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"not False"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "pyout",
"prompt_number": 27,
"text": [
"True"
]
}
],
"prompt_number": 27
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"True or False"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "pyout",
"prompt_number": 28,
"text": [
"True"
]
}
],
"prompt_number": 28
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* Comparison operators `>`, `<`, `>=` (greater or equal), `<=` (less or equal), `==` equality, `is` identical."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"2 > 1, 2 < 1"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "pyout",
"prompt_number": 29,
"text": [
"(True, False)"
]
}
],
"prompt_number": 29
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"2 > 2, 2 < 2"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "pyout",
"prompt_number": 30,
"text": [
"(False, False)"
]
}
],
"prompt_number": 30
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"2 >= 2, 2 <= 2"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "pyout",
"prompt_number": 31,
"text": [
"(True, True)"
]
}
],
"prompt_number": 31
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# equality\n",
"1 == 1"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "pyout",
"prompt_number": 109,
"text": [
"True"
]
}
],
"prompt_number": 109
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# objects identical?\n",
"a = b = 'hi'\n",
"\n",
"a is b"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "pyout",
"prompt_number": 114,
"text": [
"True"
]
}
],
"prompt_number": 114
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Compound types: Strings, List and dictionaries\n",
"\n",
"### Strings\n",
"\n",
"Strings are the variable type that is used for storing text messages. "
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"s = \"Hello world\"\n",
"type(s)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "pyout",
"prompt_number": 34,
"text": [
"str"
]
}
],
"prompt_number": 34
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# length of the string: the number of characters\n",
"len(s)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "pyout",
"prompt_number": 35,
"text": [
"11"
]
}
],
"prompt_number": 35
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# replace a substring in a string with somethign else\n",
"s2 = s.replace(\"world\", \"test\")\n",
"print s2"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"Hello test\n"
]
}
],
"prompt_number": 36
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can index a character in a string using `[]`:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"s[0]"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "pyout",
"prompt_number": 37,
"text": [
"'H'"
]
}
],
"prompt_number": 37
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Heads up MATLAB users:** Indexing start at 0!\n",
"\n",
"We can use extract a part of a string using the syntax `[start:stop]`, which extracts characters between index `start` and `stop`:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"s[0:5]"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "pyout",
"prompt_number": 38,
"text": [
"'Hello'"
]
}
],
"prompt_number": 38
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"If we omit either (or both) of `start` or `stop` from `[start:stop]`, the default is the beginning and the end of the string, respectively:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"s[:5]"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "pyout",
"prompt_number": 39,
"text": [
"'Hello'"
]
}
],
"prompt_number": 39
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"s[6:]"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "pyout",
"prompt_number": 40,
"text": [
"'world'"
]
}
],
"prompt_number": 40
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"s[:]"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "pyout",
"prompt_number": 41,
"text": [
"'Hello world'"
]
}
],
"prompt_number": 41
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can also define the step size using the syntax `[start:end:step]` (the default value for `step` is 1, as we saw above):"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"s[::1]"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "pyout",
"prompt_number": 42,
"text": [
"'Hello world'"
]
}
],
"prompt_number": 42
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"s[::2]"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "pyout",
"prompt_number": 43,
"text": [
"'Hlowrd'"
]
}
],
"prompt_number": 43
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This technique is called *slicing*. Read more about the syntax here: http://docs.python.org/release/2.7.3/library/functions.html?highlight=slice#slice"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Python has a very rich set of functions for text processing. See for example http://docs.python.org/2/library/string.html for more information."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## EXERCISE : Given a string s defined below. Make it lower case and replace any occurance of 'o' with 'a'"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"s = \"HeLlO wOrLd!\"\n",
"# TODO"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 115
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### String formatting examples"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"print \"str1\", \"str2\", \"str3\" # The print statement concatenates strings with a space"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"str1 str2 str3\n"
]
}
],
"prompt_number": 44
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"print \"str1\", 1.0, False, -1j # The print statements converts all arguments to strings"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"str1 1.0 False -1j\n"
]
}
],
"prompt_number": 45
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"print \"str1\" + \"str2\" + \"str3\" # strings added with + are concatenated without space"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"str1str2str3\n"
]
}
],
"prompt_number": 46
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"print \"value = %f\" % 1.0 # we can use C-style string formatting"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"value = 1.000000\n"
]
}
],
"prompt_number": 47
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# this formatting creates a string\n",
"s = \"value1 = %.2f. value2 = %d\" % (3.1415, 1.5)\n",
"\n",
"print s"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"value1 = 3.14. value2 = 1\n"
]
}
],
"prompt_number": 48
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# alternative, more intuitive way of formatting a string \n",
"s = 'value1 = {0}, value2 = {1}'.format(3.1415, 1.5)\n",
"\n",
"print s"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"value1 = 3.1415, value2 = 1.5\n"
]
}
],
"prompt_number": 49
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### List\n",
"\n",
"Lists are very similar to strings, except that each element can be of any type.\n",
"\n",
"The syntax for creating lists in Python is `[...]`:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"l = [1,2,3,4]\n",
"\n",
"print type(l)\n",
"print l"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"<type 'list'>\n",
"[1, 2, 3, 4]\n"
]
}
],
"prompt_number": 61
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can use the same slicing techniques to manipulate lists as we could use on strings:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"print l\n",
"\n",
"print l[1:3]\n",
"\n",
"print l[::2]"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"[1, 2, 3, 4]\n",
"[2, 3]\n",
"[1, 3]\n"
]
}
],
"prompt_number": 62
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Heads up MATLAB users:** Indexing starts at 0!"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"l[0]"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "pyout",
"prompt_number": 63,
"text": [
"1"
]
}
],
"prompt_number": 63
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Elements in a list do not all have to be of the same type:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"l = [1, 'a', 1.0, 1-1j]\n",
"print l"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"[1, 'a', 1.0, (1-1j)]\n"
]
}
],
"prompt_number": 64
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Python lists can be inhomogeneous and arbitrarily nested:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"nested_list = [1, [2, [3, [4, [5]]]]]\n",
"nested_list"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "pyout",
"prompt_number": 65,
"text": [
"[1, [2, [3, [4, [5]]]]]"
]
}
],
"prompt_number": 65
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Lists play a very important role in Python, and are for example used in loops and other flow control structures (discussed below). There are number of convenient functions for generating lists of various types, for example the `range` function:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"start = 10\n",
"stop = 30\n",
"step = 2\n",
"range(start, stop, step)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "pyout",
"prompt_number": 66,
"text": [
"[10, 12, 14, 16, 18, 20, 22, 24, 26, 28]"
]
}
],
"prompt_number": 66
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"range(-10, 10)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "pyout",
"prompt_number": 67,
"text": [
"[-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]"
]
}
],
"prompt_number": 67
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# convert a string to a list by type casting:\n",
"s2 = list(s)\n",
"s2"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "pyout",
"prompt_number": 68,
"text": [
"['v',\n",
" 'a',\n",
" 'l',\n",
" 'u',\n",
" 'e',\n",
" '1',\n",
" ' ',\n",
" '=',\n",
" ' ',\n",
" '3',\n",
" '.',\n",
" '1',\n",
" '4',\n",
" '1',\n",
" '5',\n",
" ',',\n",
" ' ',\n",
" 'v',\n",
" 'a',\n",
" 'l',\n",
" 'u',\n",
" 'e',\n",
" '2',\n",
" ' ',\n",
" '=',\n",
" ' ',\n",
" '1',\n",
" '.',\n",
" '5']"
]
}
],
"prompt_number": 68
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# sorting lists\n",
"s2.sort()\n",
"print s2"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"[' ', ' ', ' ', ' ', ' ', ',', '.', '.', '1', '1', '1', '1', '2', '3', '4', '5', '5', '=', '=', 'a', 'a', 'e', 'e', 'l', 'l', 'u', 'u', 'v', 'v']\n"
]
}
],
"prompt_number": 69
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Adding, inserting, modifying, and removing elements from lists"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# create a new empty list\n",
"l = []\n",
"\n",
"# add an elements using `append`\n",
"l.append(\"A\")\n",
"l.append(\"d\")\n",
"l.append(\"d\")\n",
"\n",
"print l"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"['A', 'd', 'd']\n"
]
}
],
"prompt_number": 70
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can modify lists by assigning new values to elements in the list. In technical jargon, lists are *mutable*."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"l[1] = \"p\"\n",
"l[2] = \"p\"\n",
"\n",
"print l"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"['A', 'p', 'p']\n"
]
}
],
"prompt_number": 71
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"l[1:3] = [\"d\", \"d\"]\n",
"\n",
"print l"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"['A', 'd', 'd']\n"
]
}
],
"prompt_number": 72
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Insert at element a specific index using `insert`"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"l.insert(0, \"i\")\n",
"l.insert(1, \"n\")\n",
"l.insert(2, \"s\")\n",
"l.insert(3, \"e\")\n",
"l.insert(4, \"r\")\n",
"l.insert(5, \"t\")\n",
"\n",
"print l"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"['i', 'n', 's', 'e', 'r', 't', 'A', 'd', 'd']\n"
]
}
],
"prompt_number": 73
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Remove first element with specific value using 'remove'"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"l.remove(\"A\")\n",
"print l"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"['i', 'n', 's', 'e', 'r', 't', 'd', 'd']\n"
]
}
],
"prompt_number": 74
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Remove an element at a specific location using `del`:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"del l[7]\n",
"del l[6]\n",
"\n",
"print l"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"['i', 'n', 's', 'e', 'r', 't']\n"
]
}
],
"prompt_number": 75
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"See `help(list)` for more details, or read the online documentation "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Tuples\n",
"\n",
"Tuples are like lists, except that they cannot be modified once created, that is they are *immutable*. \n",
"\n",
"In Python, tuples are created using the syntax `(..., ..., ...)`, or even `..., ...`:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"point = (10, 20)\n",
"\n",
"print point, type(point)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"(10, 20) <type 'tuple'>\n"
]
}
],
"prompt_number": 78
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"point = 10, 20\n",
"\n",
"print point, type(point)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"(10, 20) <type 'tuple'>\n"
]
}
],
"prompt_number": 79
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can unpack a tuple by assigning it to a comma-separated list of variables:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"x, y = point\n",
"\n",
"print \"x =\", x\n",
"print \"y =\", y"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"x = 10\n",
"y = 20\n"
]
}
],
"prompt_number": 80
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"If we try to assign a new value to an element in a tuple we get an error:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"point[0] = 20"
],
"language": "python",
"metadata": {},
"outputs": [
{
"ename": "TypeError",
"evalue": "'tuple' object does not support item assignment",
"output_type": "pyerr",
"traceback": [
"\u001b[1;31m---------------------------------------------------------------------------\u001b[0m\n\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)",
"\u001b[1;32m<ipython-input-81-ac1c641a5dca>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mpoint\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;36m0\u001b[0m\u001b[1;33m]\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;36m20\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[1;31mTypeError\u001b[0m: 'tuple' object does not support item assignment"
]
}
],
"prompt_number": 81
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Dictionaries\n",
"\n",
"Dictionaries are also like lists, except that each element is a key-value pair. The syntax for lists are `{key1 : value1, ...}`:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"params = {\"parameter1\" : 1.0,\n",
" \"parameter2\" : 2.0,\n",
" \"parameter3\" : 3.0,}\n",
"\n",
"# or equivalent\n",
"\n",
"params = dict(parameter1=1.0, parameter2=2.0, parameter3=3.0)\n",
"\n",
"print type(params)\n",
"print params"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"<type 'dict'>\n",
"{'parameter1': 1.0, 'parameter3': 3.0, 'parameter2': 2.0}\n"
]
}
],
"prompt_number": 78
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"print \"parameter1 =\", params[\"parameter1\"]\n",
"print \"parameter2 =\", params[\"parameter2\"]\n",
"print \"parameter3 =\", params[\"parameter3\"]"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"parameter1 = 1.0\n",
"parameter2 = 2.0\n",
"parameter3 = 3.0\n"
]
}
],
"prompt_number": 83
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"params[\"parameter1\"] = \"A\"\n",
"params[\"parameter2\"] = \"B\"\n",
"\n",
"# add a new entry\n",
"params[\"parameter4\"] = \"D\"\n",
"\n",
"print \"parameter1 =\", params[\"parameter1\"]\n",
"print \"parameter2 =\", params[\"parameter2\"]\n",
"print \"parameter3 =\", params[\"parameter3\"]\n",
"print \"parameter4 =\", params[\"parameter4\"]"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"parameter1 = A\n",
"parameter2 = B\n",
"parameter3 = 3.0\n",
"parameter4 = D\n"
]
}
],
"prompt_number": 79
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"\"parameter1\" in params"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "pyout",
"prompt_number": 80,
"text": [
"True"
]
}
],
"prompt_number": 80
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"params[\"parameter5\"]"
],
"language": "python",
"metadata": {},
"outputs": [
{
"ename": "KeyError",
"evalue": "'parameter5'",
"output_type": "pyerr",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m\n\u001b[0;31mKeyError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-81-a60d3a1ed350>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mparams\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;34m\"parameter5\"\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[0;31mKeyError\u001b[0m: 'parameter5'"
]
}
],
"prompt_number": 81
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Control Flow"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Conditional statements: if, elif, else\n",
"\n",
"The Python syntax for conditional execution of code use the keywords `if`, `elif` (else if), `else`:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"statement1 = False\n",
"statement2 = False\n",
"\n",
"if statement1:\n",
" print \"statement1 is True\"\n",
" \n",
"elif statement2:\n",
" print \"statement2 is True\"\n",
" \n",
"else:\n",
" print \"statement1 and statement2 are False\""
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"statement1 and statement2 are False\n"
]
}
],
"prompt_number": 85
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"For the first time, here we encounted a peculiar and unusual aspect of the Python programming language: Program blocks are defined by their indentation level. \n",
"\n",
"Compare to the equivalent C code:\n",
"\n",
" if (statement1)\n",
" {\n",
" printf(\"statement1 is True\\n\");\n",
" }\n",
" else if (statement2)\n",
" {\n",
" printf(\"statement2 is True\\n\");\n",
" }\n",
" else\n",
" {\n",
" printf(\"statement1 and statement2 are False\\n\");\n",
" }\n",
"\n",
"In C blocks are defined by the enclosing curly brakets `{` and `}`. And the level of indentation (white space before the code statements) does not matter (completely optional). \n",
"\n",
"But in Python, the extent of a code block is defined by the indentation level (ideally four white spaces). This means that we have to **be careful to indent our code correctly**, or else we will get syntax errors. \n",
"\n",
"**Examples:**"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"statement1 = statement2 = True\n",
"\n",
"if statement1:\n",
" if statement2:\n",
" print \"both statement1 and statement2 are True\""
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"both statement1 and statement2 are True\n"
]
}
],
"prompt_number": 82
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# Bad indentation!\n",
"if statement1:\n",
" if statement2:\n",
" print \"both statement1 and statement2 are True\" # this line is not properly indented"
],
"language": "python",
"metadata": {},
"outputs": [
{
"ename": "IndentationError",
"evalue": "expected an indented block (<ipython-input-83-c22a10a9b032>, line 4)",
"output_type": "pyerr",
"traceback": [
"\u001b[0;31mIndentationError\u001b[0m\u001b[0;31m:\u001b[0m expected an indented block\n"
]
}
],
"prompt_number": 83
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"statement1 = False \n",
"\n",
"if statement1:\n",
" print \"printed if statement1 is True\"\n",
" \n",
" print \"still inside the if block\""
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 84
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"if statement1:\n",
" print \"printed if statement1 is True\"\n",
" \n",
"print \"now outside the if block\""
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"now outside the if block\n"
]
}
],
"prompt_number": 85
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Loops\n",
"\n",
"In Python, loops can be programmed in a number of different ways. The most common is the `for` loop, which is used together with iterable objects, such as lists. The basic syntax is:\n",
"\n",
"\n",
"**`for` loops**:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"for x in [1,2,3]:\n",
" print x"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"1\n",
"2\n",
"3\n"
]
}
],
"prompt_number": 86
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The `for` loop iterates over the elements of the supplied list, and executes the containing block once for each element. Any kind of list can be used in the `for` loop. For example:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"for x in range(4): # by default range start at 0\n",
" print x"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"0\n",
"1\n",
"2\n",
"3\n"
]
}
],
"prompt_number": 87
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Note: `range(4)` does not include 4 !"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"for x in range(-3,3):\n",
" print x"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"-3\n",
"-2\n",
"-1\n",
"0\n",
"1\n",
"2\n"
]
}
],
"prompt_number": 88
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"for word in [\"scientific\", \"computing\", \"with\", \"python\"]:\n",
" print word"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"scientific\n",
"computing\n",
"with\n",
"python\n"
]
}
],
"prompt_number": 93
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"for x in 'Hello world!':\n",
" print x"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"H\n",
"e\n",
"l\n",
"l\n",
"o\n",
" \n",
"w\n",
"o\n",
"r\n",
"l\n",
"d\n",
"!\n"
]
}
],
"prompt_number": 116
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"To iterate over key-value pairs of a dictionary:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"for key, value in params.iteritems():\n",
" print key, \" = \", value"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"parameter4 = D\n",
"parameter1 = A\n",
"parameter3 = 3.0\n",
"parameter2 = B\n"
]
}
],
"prompt_number": 89
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Sometimes it is useful to have access to the indices of the values when iterating over a list. We can use the `enumerate` function for this:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"for idx, x in enumerate(range(-3,3)):\n",
" print idx, x"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"0 -3\n",
"1 -2\n",
"2 -1\n",
"3 0\n",
"4 1\n",
"5 2\n"
]
}
],
"prompt_number": 90
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## EXERCISE :\n",
"\n",
"* Given a string e.g. \"Hello world!\", compute the number of occurence of each letter.\n",
"* HINT : Iterate over lower case letters and use a dictionnary to count"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**List comprehensions: Creating lists using `for` loops**:\n",
"\n",
"A convenient and compact way to initialize lists:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"l1 = [x**2 for x in range(0,5)]\n",
"\n",
"print l1"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"[0, 1, 4, 9, 16]\n"
]
}
],
"prompt_number": 91
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**`while` loops**:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"i = 0\n",
"\n",
"while i < 5:\n",
" print i\n",
" \n",
" i = i + 1\n",
" \n",
"print \"done\""
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"0\n",
"1\n",
"2\n",
"3\n",
"4\n",
"done\n"
]
}
],
"prompt_number": 92
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Note that the `print \"done\"` statement is not part of the `while` loop body because of the difference in indentation."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Functions\n",
"\n",
"A function in Python is defined using the keyword `def`, followed by a function name, a signature within parenthises `()`, and a colon `:`. The following code, with one additional level of indentation, is the function body."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"def func0(): \n",
" print \"test\""
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 93
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"func0()"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"test\n"
]
}
],
"prompt_number": 99
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Optionally, but highly recommended, we can define a so called \"docstring\", which is a description of the functions purpose and behaivor. The docstring should follow directly after the function definition, before the code in the function body."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"def func1(s):\n",
" \"\"\"\n",
" Print a string 's' and tell how many characters it has \n",
" \"\"\"\n",
" print s, \"has\", len(s), \"characters\""
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 94
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"help(func1)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"Help on function func1 in module __main__:\n",
"\n",
"func1(s)\n",
" Print a string 's' and tell how many characters it has\n",
"\n"
]
}
],
"prompt_number": 95
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"func1(\"test\")"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"test has 4 characters\n"
]
}
],
"prompt_number": 102
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Functions that returns a value use the `return` keyword:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"def square(x):\n",
" \"\"\"\n",
" Return the square of x.\n",
" \"\"\"\n",
" return x ** 2"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 103
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"square(4)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "pyout",
"prompt_number": 104,
"text": [
"16"
]
}
],
"prompt_number": 104
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can return multiple values from a function using tuples (see above):"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"def powers(x):\n",
" \"\"\"\n",
" Return a few powers of x.\n",
" \"\"\"\n",
" return x ** 2, x ** 3, x ** 4"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 97
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"powers(3)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "pyout",
"prompt_number": 98,
"text": [
"(9, 27, 81)"
]
}
],
"prompt_number": 98
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"x2, x3, x4 = powers(3)\n",
"print x3"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"27\n"
]
}
],
"prompt_number": 99
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## EXERCISE : Write the factorial function fact(n) = n * (n-1) * (n-2) * 1\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Default argument and keyword arguments"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"def myfunc(x, p=2, debug=False): # debug has a default value = False\n",
" if debug:\n",
" print \"evaluating myfunc for x =\", x, \"using exponent p =\", p\n",
" return x**p"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 100
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"If we don't provide a value of the `debug` argument when calling the the function `myfunc` it defaults to the value provided in the function definition:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"myfunc(5)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "pyout",
"prompt_number": 101,
"text": [
"25"
]
}
],
"prompt_number": 101
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"myfunc(5, debug=True)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"evaluating myfunc for x = 5 using exponent p = 2\n"
]
},
{
"output_type": "pyout",
"prompt_number": 102,
"text": [
"25"
]
}
],
"prompt_number": 102
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### *keyword* arguments : If we explicitly list the name of the arguments in the function calls, they do not need to come in the same order as in the function definition."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"myfunc(p=3, debug=True, x=7)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"evaluating myfunc for x = 7 using exponent p = 3\n"
]
},
{
"output_type": "pyout",
"prompt_number": 111,
"text": [
"343"
]
}
],
"prompt_number": 111
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# map is a built-in python function\n",
"map(lambda x: x**2, range(-3,4))"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "pyout",
"prompt_number": 114,
"text": [
"[9, 4, 1, 0, 1, 4, 9]"
]
}
],
"prompt_number": 114
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Classes\n",
"\n",
"Classes are the key features of object-oriented programming. A class is a structure for representing an object and the operations that can be performed on the object. \n",
"\n",
"In Python a class can contain *attributes* (variables) and *methods* (functions).\n",
"\n",
"In python a class are defined almost like a functions, but using the `class` keyword, and the class definition usually contains a number of class method definitions (a function in a class).\n",
"\n",
"* Each class method should have an argurment `self` as it first argument. This object is a self-reference.\n",
"\n",
"* Some class method names have special meaning, for example:\n",
"\n",
" * `__init__`: The name of the method that is invoked when the object is first created.\n",
" * `__str__` : A method that is invoked when a simple string representation of the class is needed, as for example when printed.\n",
" * There are many more, see http://docs.python.org/2/reference/datamodel.html#special-method-names"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"class Point:\n",
" \"\"\"\n",
" Simple class for representing a point in a Cartesian coordinate system.\n",
" \"\"\"\n",
" \n",
" def __init__(self, x, y):\n",
" \"\"\"\n",
" Create a new Point at x, y.\n",
" \"\"\"\n",
" self.x = x\n",
" self.y = y\n",
" \n",
" def translate(self, dx, dy):\n",
" \"\"\"\n",
" Translate the point by dx and dy in the x and y direction.\n",
" \"\"\"\n",
" self.x += dx\n",
" self.y += dy\n",
" \n",
" def __str__(self):\n",
" return \"Point at [%f, %f]\" % (self.x, self.y)"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 115
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"To create a new instance of a class:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"p1 = Point(0, 0) # this will invoke the __init__ method in the Point class\n",
"\n",
"print p1 # this will invode the __str__ method"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"Point at [0.000000, 0.000000]\n"
]
}
],
"prompt_number": 116
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"To invoke a class method in the class instance `p`:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"p2 = Point(1, 1)\n",
"\n",
"p1.translate(0.25, 1.5)\n",
"\n",
"print p1\n",
"print p2"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"Point at [0.250000, 1.500000]\n",
"Point at [1.000000, 1.000000]\n"
]
}
],
"prompt_number": 117
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Note that calling class methods can modifiy the state of the that particular class instance, but does not effect other class instances or any global variables.\n",
"\n",
"That is one of the nice things about object-oriented design: code such as functions and related variables are group in separate and independent entities. "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Exceptions\n",
"\n",
"In Python errors are managed with a special language construct called \"Exceptions\". When errors occur exceptions can be raised, which interrupts the normal program flow and fallback to somewhere else in the code where the closest try-except statements is defined.\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"To generate an exception we can use the `raise` statement, which takes an argument that must be an instance of the class `BaseExpection` or a class dervied from it. "
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"raise Exception(\"description of the error\")"
],
"language": "python",
"metadata": {},
"outputs": [
{
"ename": "Exception",
"evalue": "description of the error",
"output_type": "pyerr",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m\n\u001b[0;31mException\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-103-8f47ba831d5a>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0;32mraise\u001b[0m \u001b[0mException\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"description of the error\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[0;31mException\u001b[0m: description of the error"
]
}
],
"prompt_number": 103
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"A typical use of exceptions is to abort functions when some error condition occurs, for example:\n",
"\n",
" def my_function(arguments):\n",
" \n",
" if not verify(arguments):\n",
" raise Expection(\"Invalid arguments\")\n",
" \n",
" # rest of the code goes here"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"To gracefully catch errors that are generated by functions and class methods, or by the Python interpreter itself, use the `try` and `expect` statements:\n",
"\n",
" try:\n",
" # normal code goes here\n",
" except:\n",
" # code for error handling goes here\n",
" # this code is not executed unless the code\n",
" # above generated an error\n",
"\n",
"For example:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"try:\n",
" print \"test\"\n",
" # generate an error: the variable test is not defined\n",
" print test\n",
"except:\n",
" print \"Caught an expection\""
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"test\n",
"Caught an expection\n"
]
}
],
"prompt_number": 104
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"To get information about the error, we can access the `Expection` class instance that describes the exception by using for example:\n",
"\n",
" except Exception as e:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"try:\n",
" print \"test\"\n",
" # generate an error: the variable test is not defined\n",
" print test\n",
"except Exception as e:\n",
" print \"Caught an expection:\", e"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"test\n",
"Caught an expection: name 'test' is not defined\n"
]
}
],
"prompt_number": 105
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Further reading\n",
"\n",
"* http://www.python.org - The official web page of the Python programming language.\n",
"* http://www.python.org/dev/peps/pep-0008 - Style guide for Python programming. Highly recommended. \n",
"* http://www.greenteapress.com/thinkpython/ - A free book on Python programming.\n",
"* [Python Essential Reference](http://www.amazon.com/Python-Essential-Reference-4th-Edition/dp/0672329786) - A good reference book on Python programming."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [],
"language": "python",
"metadata": {},
"outputs": []
}
],
"metadata": {}
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment