First commit notebooks for python

pull/1/head
cif2cif 8 years ago
commit f71e7e167b

@ -0,0 +1,124 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"![](http://www.upm.es/sfs/Rectorado/Gabinete%20del%20Rector/Logos/UPM/EscPolitecnica/EscUpmPolit_p.gif \"UPM\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Course Notes for Learning Intelligent Systems"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Department of Telematic Engineering Systems, Universidad Politécnica de Madrid, © 2015 Carlos A. Iglesias"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Introduction to Python"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This lecture provides a quick introduction to programming in Python as well as the programming environment used in the course."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Table of Contents"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"1. [Install the environment and Intro to Notebooks](1_1_Notebooks.ipynb)\n",
"2. Intro to Python\n",
" 1. Built-in Types\n",
" 1. [Booleans, numbers and strings](1_2_Numbers_Strings.ipynb)\n",
" 2. [Sequences (lists, tuples and range)](1_3_Sequences.ipynb)\n",
" 3. [Sets (set, frozenset) and Mappings (dictionary)](1_4_Sets.ipynb)\n",
" 2. [Control flow statements](1_5_ControlFlow.ipynb)\n",
" 3. [Functions](1_6_Functions.ipynb)\n",
" 4. [Variables](1_7_Variables.ipynb)\n",
" 5. [Classes](1_8_Classes.ipynb)\n",
" 6. [Errors and Exceptions](1_9_Errors_Exceptions.ipynb)\n",
" 7. [Modules and Packages](1__10_Modules_Packages.ipynb)\n",
" 8. Testing / Generadores / Decoradores"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# References"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* [The Python tutorial](https://docs.python.org/3/tutorial/)\n",
"* [Object-Oriented Programming in Python](http://python-textbok.readthedocs.org/en/latest/index.html)\n",
"* [Python3 tutorial](http://www.python-course.eu/python3_course.php)\n",
"* [Python for the Busy Java Developer, Deepak Sarda, 2014](http://antrix.net/static/pages/python-for-java/online/)\n",
"* [Style Guide for Python Code (PEP-0008)](https://www.python.org/dev/peps/pep-0008/)\n",
"* [Python Slides](http://tdc-www.harvard.edu/Python.pdf)\n",
"* [Python for Programmers - 1 day course](http://www.ucs.cam.ac.uk/docs/course-notes/unix-courses/archived/archived-python-courses/PythonProgIntro/files/notes.pdf)\n",
"* [Dive into Python 3, Mark Pilgrim, 2009](http://www.diveintopython3.net/)\n",
"* [Think Python: How to Think Like a Computer Scientist](http://www.greenteapress.com/thinkpython/html/index.html)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Licence"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The notebook is freely licensed under under the [Creative Commons Attribution Share-Alike license](https://creativecommons.org/licenses/by/2.0/). \n",
"\n",
"© 2015 Carlos A. Iglesias, Universidad Politécnica de Madrid."
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.5.1"
}
},
"nbformat": 4,
"nbformat_minor": 0
}

@ -0,0 +1,188 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"![](http://www.upm.es/sfs/Rectorado/Gabinete%20del%20Rector/Logos/UPM/EscPolitecnica/EscUpmPolit_p.gif \"UPM\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Course Notes for Learning Intelligent Systems"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Department of Telematic Engineering Systems, Universidad Politécnica de Madrid, © 2015 Carlos A. Iglesias"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# How to install the environment and play with notebooks"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In this lecture we will learn (i) how to set up your environment and (ii) how to run notebooks and use them"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# 1. Set up the environment"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"1. Install Anaconda \n",
"* Download the suitable version for your operating system of Python 3 at https://www.continuum.io/downloads\n",
"* Follow the installation instructions. In Linux/Mac, launch a terminal and execute the installer script.\n",
"2. [Optional, anaconda already installs jupyter] Install Jupyter http://jupyter.readthedocs.org/en/latest/install.html\n",
"* Launch a terminal and execute 'conda install jupyter'"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# 2. Notebooks in a nutshell"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 2.1 Launching jupyter"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"1. Launch a terminal from the directory you have your notebook (file extension .ipynb) or you want to create your notebook\n",
"1. Write (without '') 'jupyter notebook' and press click"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In case you have not installed the environment, you can run Jupyter here https://try.jupyter.org/"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 2.2 Running notebooks"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can create, open or save notebooks from the menu File."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Notebooks have two main types of cells: code (executable) and text (called 'markdown'). You can change the type of a cell in the toolbar. A detailed user manual of Jupyter can be found here: \n",
"* http://jupyter.cs.brynmawr.edu/hub/dblank/public/Jupyter%20Notebook%20Users%20Manual.ipynb\n",
"* http://jupyter-notebook.readthedocs.org/en/latest/notebook.html"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"For executing a 'code' cell, you can\n",
"* press Shift+Enter\n",
"* click on the 'run cell' button of the toolbar, or \n",
"* select the Cell-Run menu item"
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": true
},
"source": [
"Example: we use Jupyter as a calculator, let's execute 2+2"
]
},
{
"cell_type": "raw",
"metadata": {},
"source": [
"2+2"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's try: write 2+2 in the cell below and execute the cell"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Licence"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The notebook is freely licensed under under the [Creative Commons Attribution Share-Alike license](https://creativecommons.org/licenses/by/2.0/). \n",
"\n",
"© 2015 Carlos A. Iglesias, Universidad Politécnica de Madrid."
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.4.3+"
}
},
"nbformat": 4,
"nbformat_minor": 0
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

@ -0,0 +1,624 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"![](http://www.upm.es/sfs/Rectorado/Gabinete%20del%20Rector/Logos/UPM/EscPolitecnica/EscUpmPolit_p.gif \"UPM\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Course Notes for Learning Intelligent Systems"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Department of Telematic Engineering Systems, Universidad Politécnica de Madrid, © 2015 Carlos A. Iglesias"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Built-in Types: Sets and Mappings"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* *Sets* are unordered bags of values\n",
"* *Dictionaries* are unordered bags of key-values pairs\n",
"\n",
"A set object is an unordered collection of distinct objects. There are two built-in set types: **set** (mutable) and **frozenset** (inmutable).\n",
"\n",
"A mapping object maps hashable values to arbitrary objects. Mappings are mutable objects. There is only one bultin mapping type: **dictionary**."
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": true
},
"source": [
"## 1. Sets"
]
},
{
"cell_type": "code",
"execution_count": 413,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"set()"
]
},
"execution_count": 413,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"my_set = set() #create a set\n",
"my_set"
]
},
{
"cell_type": "code",
"execution_count": 414,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"{1}"
]
},
"execution_count": 414,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"my_set.add(1) # add an element\n",
"my_set"
]
},
{
"cell_type": "code",
"execution_count": 415,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"my_set.add(2) # add another element"
]
},
{
"cell_type": "code",
"execution_count": 416,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"{1, 2}"
]
},
"execution_count": 416,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"my_set"
]
},
{
"cell_type": "code",
"execution_count": 417,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"{1, 2, 3}"
]
},
"execution_count": 417,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"my_set.add(3) # add another one\n",
"my_set"
]
},
{
"cell_type": "code",
"execution_count": 418,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"{1, 2, 3}"
]
},
"execution_count": 418,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"my_set.add(1) #try to add a repeated element\n",
"my_set"
]
},
{
"cell_type": "code",
"execution_count": 419,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}"
]
},
"execution_count": 419,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"s2 = set(range(10)) # we can create a set from a range\n",
"s2"
]
},
{
"cell_type": "code",
"execution_count": 420,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"l = ['a', 'a', 'b', 'c', 'c', 'c']"
]
},
{
"cell_type": "code",
"execution_count": 421,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"{'a', 'b', 'c'}"
]
},
"execution_count": 421,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"s3 = set(l) # if we create a set from a list, elements are not repeated\n",
"s3"
]
},
{
"cell_type": "code",
"execution_count": 422,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"3"
]
},
"execution_count": 422,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"len(s3) "
]
},
{
"cell_type": "code",
"execution_count": 423,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"{0, 1, 2, 3, 4, 5, 'c', 6, 7, 8, 9, 'a', 'b'}"
]
},
"execution_count": 423,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"s3.union(s2) # we can use set methods: union(), intersection(), difference(), ..."
]
},
{
"cell_type": "code",
"execution_count": 424,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 424,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"3 in my_set #check membership"
]
},
{
"cell_type": "code",
"execution_count": 425,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"set"
]
},
"execution_count": 425,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"type(s3)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 2. Dictionaries"
]
},
{
"cell_type": "code",
"execution_count": 426,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"{'key1': 1, 'key2': 2, 'key3': 3}"
]
},
"execution_count": 426,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"my_dictionary = {'key1': 1, 'key2': 2, 'key3': 3} # pairs of key-value mappings\n",
"my_dictionary"
]
},
{
"cell_type": "code",
"execution_count": 427,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"1"
]
},
"execution_count": 427,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"my_dictionary['key1'] #retrieve a value given a key"
]
},
{
"cell_type": "code",
"execution_count": 428,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"{'key1': 1, 'key2': 2, 'key3': 3}"
]
},
"execution_count": 428,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"my_dict = dict()\n",
"my_dict['key1'] = 1\n",
"my_dict['key2'] = 2\n",
"my_dict['key3'] = 3\n",
"my_dict # alternative way to create a dictionary "
]
},
{
"cell_type": "code",
"execution_count": 429,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 429,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"my_dict == my_dictionary # check if both dictionaries are equal"
]
},
{
"cell_type": "code",
"execution_count": 430,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"{'one': {'two': {'three': 'Nested dict'}}}"
]
},
"execution_count": 430,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"my_dict2 = {'one': {'two': {'three': 'Nested dict'}}} #nested dictionary\n",
"my_dict2"
]
},
{
"cell_type": "code",
"execution_count": 431,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"'Nested dict'"
]
},
"execution_count": 431,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"my_dict2['one']['two']['three'] #access the value"
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": false
},
"source": [
"Dictionaries have different methods, check them with Tab."
]
},
{
"cell_type": "code",
"execution_count": 473,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"dict_keys(['key2', 'key3', 'key1'])"
]
},
"execution_count": 473,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"my_dict.keys() # in Python3 we get a View object that changes when the dictionary changes"
]
},
{
"cell_type": "code",
"execution_count": 478,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"['key2', 'key3', 'key1']"
]
},
"execution_count": 478,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"list(my_dict.keys()) # we can convert it to a list, we see dicionaries are unordered"
]
},
{
"cell_type": "code",
"execution_count": 474,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"dict_values([2, 3, 1])"
]
},
"execution_count": 474,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"my_dict.values()"
]
},
{
"cell_type": "code",
"execution_count": 476,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"[2, 3, 1]"
]
},
"execution_count": 476,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"list(my_dict.values())"
]
},
{
"cell_type": "code",
"execution_count": 479,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"dict"
]
},
"execution_count": 479,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"type(my_dict)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Licence"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The notebook is freely licensed under under the [Creative Commons Attribution Share-Alike license](https://creativecommons.org/licenses/by/2.0/). \n",
"\n",
"© 2015 Carlos A. Iglesias, Universidad Politécnica de Madrid."
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.4.3+"
}
},
"nbformat": 4,
"nbformat_minor": 0
}

@ -0,0 +1,698 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"![](http://www.upm.es/sfs/Rectorado/Gabinete%20del%20Rector/Logos/UPM/EscPolitecnica/EscUpmPolit_p.gif \"UPM\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Course Notes for Learning Intelligent Systems"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Department of Telematic Engineering Systems, Universidad Politécnica de Madrid, © 2015 Carlos A. Iglesias"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Control Flow statements"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Python ends a statement with a colon (:) and blocks are denoted by the level of indentation. "
]
},
{
"cell_type": "raw",
"metadata": {},
"source": [
"Example in Java:\n",
"\n",
"if (a < c) {\n",
" a++;\n",
" b++;\n",
"}\n"
]
},
{
"cell_type": "raw",
"metadata": {},
"source": [
"Example in Python: (observe: no parenthesis (), no ending semicolons (;) but a colon is used (:)\n",
"if a < c:\n",
" a++\n",
" b++"
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": true
},
"source": [
"## 1. Conditional statements: if, elif, else"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"9"
]
},
"execution_count": 22,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import random # import random before using it\n",
"x = random.randrange(1, 10) # generate a random integer between [1, 10] (both included)\n",
"x"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Too small\n"
]
}
],
"source": [
"# Execute several times in order the previous cell and this one\n",
"if x < 5:\n",
" print(\"Too small\")\n",
"elif x == 5:\n",
" print(\"Just in the middle\")\n",
"else: \n",
" print(\"Too big\")"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Too small\n"
]
}
],
"source": [
"# Only one branch\n",
"if x <= 5:\n",
" print(\"Too small\")\n",
"else:\n",
" print(\"Too big\")"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Too big\n"
]
}
],
"source": [
"# Python has no switch statement for multiple branches\n",
"if x <= 4:\n",
" print(\"Too small\")\n",
"elif x <= 5:\n",
" print(\"Small\")\n",
"elif x <= 7:\n",
" print (\"Big\")\n",
"else:\n",
" print(\"Too big\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 2. Loops: for, while"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 2.1. For"
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0\n",
"1\n",
"2\n",
"3\n",
"4\n",
"5\n",
"6\n",
"7\n",
"8\n",
"9\n"
]
}
],
"source": [
"# for with ranges\n",
"for i in range(10): \n",
" print(i)"
]
},
{
"cell_type": "code",
"execution_count": 29,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1\n",
"2\n",
"3\n",
"4\n"
]
}
],
"source": [
"# for with lists\n",
"l = [1, 2, 3, 4]\n",
"for i in l:\n",
" print(i)"
]
},
{
"cell_type": "code",
"execution_count": 30,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1\n",
"a\n",
"b\n"
]
}
],
"source": [
"# for with tuples\n",
"t = (1, 'a', 'b')\n",
"for i in t:\n",
" print(i)"
]
},
{
"cell_type": "code",
"execution_count": 31,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"k2\n",
"k1\n",
"k3\n"
]
}
],
"source": [
"# for with dictionaries\n",
"d = {'k1':'v1', 'k2':'v2', 'k3':'v3'}\n",
"for i in d:\n",
" print(i)"
]
},
{
"cell_type": "code",
"execution_count": 34,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"k2 v2\n",
"k1 v1\n",
"k3 v3\n"
]
}
],
"source": [
"# We get only the keys. If we want the pairs we need to create a generator (we will see this later)\n",
"for k,v in d.items():\n",
" print(k, v)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 2.2. While"
]
},
{
"cell_type": "code",
"execution_count": 56,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"5\n",
"4\n",
"3\n",
"2\n"
]
}
],
"source": [
"x = 5\n",
"while x > 1:\n",
" print(x)\n",
" x -= 1 # Python does not have x--"
]
},
{
"cell_type": "code",
"execution_count": 45,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"2\n",
"3\n",
"4\n"
]
}
],
"source": [
"# Else is optional\n",
"x = 2\n",
"while x < 5: \n",
" print(x)\n",
" x += 1"
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": false
},
"source": [
"### 2.3. Break, continue, pass\n",
"\n",
"* **break**: break out of the smallest enclosing loop (for or while)\n",
"* **continue**: continue with the next iteration of the loop\n",
"* **pass**: do nothing\n",
"\n",
"Both *for* and *while* can include an optional statement else which is executed always unless a break statement is reached"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Goal found at index c\n",
"End loop\n"
]
}
],
"source": [
"# Example find an element, else executed at the end\n",
"list = ['a', 'b', 'c']\n",
"goal = 'c'\n",
"for i in list:\n",
" if i == goal:\n",
" print('Goal found at index', i)\n",
"else:\n",
" print('End loop')"
]
},
{
"cell_type": "code",
"execution_count": 58,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"End loop\n"
]
}
],
"source": [
"# Example else\n",
"list = []\n",
"goal = 'c'\n",
"for i in list:\n",
" if i == goal:\n",
" print('Goal found at index', i)\n",
"else:\n",
" print('End loop')"
]
},
{
"cell_type": "code",
"execution_count": 60,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Goal found at index c\n"
]
}
],
"source": [
"# We improve above code with break\n",
"# Example else\n",
"list = ['a', 'b', 'c']\n",
"goal = 'c'\n",
"for i in list:\n",
" if i == goal:\n",
" print('Goal found at index', i)\n",
" break\n",
"else:\n",
" print('Goal not found')"
]
},
{
"cell_type": "code",
"execution_count": 62,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Goal not found\n"
]
}
],
"source": [
"# We improve above code with break\n",
"# Example else\n",
"list = ['a', 'b', 'c']\n",
"goal = 'e'\n",
"for i in list:\n",
" if i == goal:\n",
" print('Goal found at index', i)\n",
" break\n",
"else:\n",
" print('Goal not found')"
]
},
{
"cell_type": "code",
"execution_count": 50,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1\n",
"2\n",
"4\n",
"5\n",
"7\n",
"8\n",
"10\n",
"11\n",
"13\n",
"14\n"
]
}
],
"source": [
"# Print numbers from 0 to 15 which are not multiple of 3\n",
"for i in range(15):\n",
" if i % 3 == 0:\n",
" continue\n",
" print(i)"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Found 4\n"
]
}
],
"source": [
"# Find the first occurrence of an element in a list\n",
"l = [1, 2, 3, 4, 1, 2]\n",
"goal = 4\n",
"for n in l:\n",
" if n == 4:\n",
" print(\"Found\", n)\n",
" break\n",
"else:\n",
" print(\"Not found\")"
]
},
{
"cell_type": "code",
"execution_count": 64,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Big\n"
]
}
],
"source": [
"# Example of pass, when we do not want to do anything\n",
"x = 4\n",
"if x < 2:\n",
" print(\"Low\")\n",
"elif x >= 2:\n",
" print(\"Big\")\n",
"else:\n",
" pass"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 3. List comprehension\n",
"\n",
"List comprehension are a simple way to create lists like we describe vectors in mathematics.\n",
"\n",
"S = {x² : x in {0 ... 9}}\n",
"\n",
"M = {x | x in S and x even}"
]
},
{
"cell_type": "code",
"execution_count": 71,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]"
]
},
"execution_count": 71,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Syntax: first what we want to include in the list (x) and then how to obtain x\n",
"# list = {x : x in {0 ... 9}}\n",
"list = [x for x in range(10)]\n",
"list"
]
},
{
"cell_type": "code",
"execution_count": 70,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]"
]
},
"execution_count": 70,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# list = {x² : x in {0 ... 9}}\n",
"list = [x*x for x in range(10)]\n",
"list"
]
},
{
"cell_type": "code",
"execution_count": 72,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"[0, 4, 16, 36, 64]"
]
},
"execution_count": 72,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# list = {x² : x in {0 ... 9}, x is even}\n",
"list = [x*x for x in range(10) if x % 2 == 0]\n",
"list"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Licence"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The notebook is freely licensed under under the [Creative Commons Attribution Share-Alike license](https://creativecommons.org/licenses/by/2.0/). \n",
"\n",
"© 2015 Carlos A. Iglesias, Universidad Politécnica de Madrid."
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.5.1"
}
},
"nbformat": 4,
"nbformat_minor": 0
}

@ -0,0 +1,490 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"![](http://www.upm.es/sfs/Rectorado/Gabinete%20del%20Rector/Logos/UPM/EscPolitecnica/EscUpmPolit_p.gif \"UPM\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Course Notes for Learning Intelligent Systems"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Department of Telematic Engineering Systems, Universidad Politécnica de Madrid, © 2015 Carlos A. Iglesias"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Functions"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"A function is a sequence of statements which performs some kind of task.\n",
"\n",
"They have optional parameters and an optional return value. If no return is provided, the default return value is *NoneType*.\n",
"\n",
"In Python we cannot overload a function. Functions are just names (variables) and cannot have two implementations at the same time. If you declare twice a function, the second declaration overrides the first one. Nevertheless, we can declare default values or variable arguments, which are the main use of overloading."
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"5\n"
]
}
],
"source": [
"def sum(a, b):\n",
" return a + b\n",
"c = sum(2,3)\n",
"print(c)"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"5\n"
]
}
],
"source": [
"#keyword parameters\n",
"d = sum(a=2, b=3)\n",
"print(d)"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"***\n",
"hi\n",
"***\n"
]
}
],
"source": [
"def greetings():\n",
" print('***')\n",
" print('hi')\n",
" print('***')\n",
"\n",
"greetings()"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"***\n",
"hi\n",
"***\n"
]
}
],
"source": [
"# We can assign a function to a variable. Fun\n",
"d = greetings()"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"NoneType"
]
},
"execution_count": 14,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"type(d)"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"function"
]
},
"execution_count": 16,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"type(greetings)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Function documentation\n",
"The first statement in the body of a function is usually a documentation triple-quoted string, called *docstring*, which can be accessed with function_name.\\__doc__. "
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[3, 2, 1]\n",
"Receives a list and returns the list in reverse order\n"
]
}
],
"source": [
"def reverse(l):\n",
" \"\"\"Receives a list and returns the list in reverse order\"\"\"\n",
" return l[::-1]\n",
"\n",
"l = [1, 2, 3]\n",
"d = reverse(l)\n",
"print(d)\n",
"print(reverse.__doc__)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Default parameters\n",
"\n",
"We can define default parameters by assigning a value to a parameter in the function definition"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"2\n",
"5\n"
]
}
],
"source": [
"def sum(a, b=0):\n",
" return a + b\n",
"print(sum(2))\n",
"print(sum(2,3))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Variable number of arguments"
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1\n",
"6\n"
]
}
],
"source": [
"#variable number of arguments: *\n",
"def sum(a, *l):\n",
" \"\"\"Sum of a non empty list of arbitrary numbers\"\"\"\n",
" total = a\n",
" for num in l:\n",
" total += num\n",
" return total\n",
"print(sum(1))\n",
"print(sum(1,2,3))"
]
},
{
"cell_type": "code",
"execution_count": 28,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"7\n",
"13\n"
]
}
],
"source": [
"#Packing \n",
"l = [1, 2, 3]\n",
"print(sum(1, *l)) # same than sum(1, 1, 2, 3)\n",
"\n",
"t = (4, 4, 4)\n",
"print(sum(1, *t))"
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": true
},
"source": [
"## Lambda functions\n",
"\n",
"Lambda functions are anonymous functions. They are used as mini-functions with abbreviated syntax"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"c 27\n",
"c 27\n"
]
}
],
"source": [
"def sq(x):\n",
" return x**x\n",
"c = sq(3)\n",
"print('c', c)\n",
"\n",
"# lambda equivalent\n",
"sq = lambda x : x**x\n",
"c = sq(3)\n",
"print('c', c)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Formatted output: print\n",
"\n",
"\n",
"The arguments of the print function are the following ones:\n",
"\n",
"**print(value1, ..., sep='&nbsp;&nbsp;', end='\\n')**\n",
"\n",
"* it can receive a variable number of arguments (value1, value2, ...)\n",
"* *sep*: separator of values (default: ' ')\n",
"* *end*: final character (default: new line)\n",
"\n",
"In Python2, print was not a function, it was a statement, so it was used without parameters: \n",
"\n",
"print x\n",
"\n",
"If you want to use the print syntax in Python2, you can import the print function to make it compatible with Python3: \n",
"\n",
"from \\__future\\__ import print_fuction "
]
},
{
"cell_type": "code",
"execution_count": 33,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1 2 3 4\n",
"1,2,3,4\n",
"1,2,3,4#1|2|3|4\n"
]
}
],
"source": [
"print(1, 2, 3, 4)\n",
"print(1, 2, 3, 4, sep=',')\n",
"print(1, 2, 3, 4, sep=',', end=\"#\")\n",
"print(1, 2, 3, 4, sep='|')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can use [**format**](https://pyformat.info/) for string formatting."
]
},
{
"cell_type": "code",
"execution_count": 41,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Number: 1,2\n",
"PI #3.141592653589793#\n",
"PI # 3.14#\n"
]
}
],
"source": [
"import math\n",
"print('Number: {},{}'.format(1, 2)) #replaces [] inside the string by the arguments of format\n",
"print('PI #{}#'.format(math.pi))\n",
"print('PI #{:5.2f}#'.format(math.pi)) # at least 5 characters with two decimals"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Input: input\n",
"\n",
"User input can be collected with **input**."
]
},
{
"cell_type": "code",
"execution_count": 45,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Enter a number 5\n",
"5\n"
]
}
],
"source": [
"num = input('Enter a number ')\n",
"print(num)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Licence"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The notebook is freely licensed under under the [Creative Commons Attribution Share-Alike license](https://creativecommons.org/licenses/by/2.0/). \n",
"\n",
"© 2015 Carlos A. Iglesias, Universidad Politécnica de Madrid."
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.5.1"
}
},
"nbformat": 4,
"nbformat_minor": 0
}

@ -0,0 +1,330 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"![](http://www.upm.es/sfs/Rectorado/Gabinete%20del%20Rector/Logos/UPM/EscPolitecnica/EscUpmPolit_p.gif \"UPM\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Course Notes for Learning Intelligent Systems"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Department of Telematic Engineering Systems, Universidad Politécnica de Madrid, © 2015 Carlos A. Iglesias"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Variables"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 1. Strongly typed and dynamically typed"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"As we have seen previously, in Python we can assign an object to a variable with the assignment operator (=).\n",
"\n",
"Binding a variable in Python means setting a name to hold a reference to some object. Assignment creates references, not copies.\n",
"\n",
"Names in Python do not have an intrinsic type. Objects have types. Python determines the type of the reference automatically based on the data object assigned to it.\n",
"\n",
"In Python, everything is an object, there no difference between primitive types, functions and objects: all are objects."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"a = 2\n",
"a"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Python is a **strongly typed** language and **dynamically typed** language.\n",
"\n",
"This means:\n",
"* ** dynamically typed**: variables do not declare a static type (as in Java int a = 2;). Variables have no type themselves, they are just names that hold a reference to some object. The type of the variable is changed dynamically when you change the type of the assigned data object. \n",
"* **strongly typed**: the interpreter tracks variable types. There is no explicit type conversion. For example, in Javascript we can "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"type(a)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Exercises"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Can we assign a String value to the variable a? \n",
"Can we assign the expression 'd' + 3 to the variable a?\n",
"\n",
"\n",
"Give reasons for your answers and check them below."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"a = 'd'\n",
"a"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"a = 'd' + 3\n",
"a"
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": true
},
"source": [
"## 2. Mutability"
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": false
},
"source": [
"Objects whose value can change are said to be **mutable**; objects whose value is unchangeable once they are created are called **immutable**.\n",
"\n",
"* **Mutable types**: integers, floats, strings, tuples\n",
"* **Inmutable types**: lists, dictionaries"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# Exercise mutable type\n",
"a = 10\n",
"b = a\n",
"b = 5\n",
"print('a', a)\n",
"print('b', b)\n",
"\n",
"# Which will be the values of a and b?"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# Exercise mutable type\n",
"a = 10\n",
"a = 10 + 1\n",
"print(a)\n",
"\n",
"# Can we change 'a' if it is inmutable?"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# Exercise mutable type\n",
"a = \"Hola\"\n",
"b = a\n",
"b = \"Hi\"\n",
"print('a', a)\n",
"print('b', b)\n",
"\n",
"# Which will be the values of a and b?"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# Exercise inmutable type\n",
"a = [1, 2, 3]\n",
"b = a\n",
"a.append(4)\n",
"print('a', a)\n",
"print('b', b)\n",
"\n",
"# Which will be the value "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 3. Scope"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# Example of a local variable\n",
"# The scope defines the visibility of a name within a block. \n",
"# If a local variable is defined in a block, its scope includes that block. \n",
"\n",
"c = 3\n",
"def add(a, b):\n",
" c = a + b\n",
" return c\n",
"d = add(2, 2)\n",
"print('d', d)\n",
"print('c', c)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# Access global variables\n",
"\n",
"c = 3\n",
"def add(a, b):\n",
" global c\n",
" c = a + b\n",
" return c\n",
"d = add(2, 2)\n",
"print('d', d)\n",
"print('c', c)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 4. Constants\n",
"\n",
"In Python there is no way to specify that a variable is constant, but there is the convention to write their names in all caps, with underscores separating words."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"NUMBER_OF_LIFES = 5\n",
"\n",
"print(NUMBER_OF_LIFES)\n",
"\n",
"# built-in constants usually do no follow the convention \n",
"import math\n",
"print(math.pi)\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Licence"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The notebook is freely licensed under under the [Creative Commons Attribution Share-Alike license](https://creativecommons.org/licenses/by/2.0/). \n",
"\n",
"© 2015 Carlos A. Iglesias, Universidad Politécnica de Madrid."
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.5.1"
}
},
"nbformat": 4,
"nbformat_minor": 0
}

@ -0,0 +1,345 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"![](http://www.upm.es/sfs/Rectorado/Gabinete%20del%20Rector/Logos/UPM/EscPolitecnica/EscUpmPolit_p.gif \"UPM\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Course Notes for Learning Intelligent Systems"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Department of Telematic Engineering Systems, Universidad Politécnica de Madrid, © 2015 Carlos A. Iglesias"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Classes\n",
"\n",
"In Python everthing is an object. Classes allow programmers to define their own object types.\n",
"\n",
"Classes are defined with the **class** reserved keyword."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Instance attributes and methods\n",
"\n",
"The first argument of instance class method is self, that refers to the current instance of the class.\n",
"There is a special method, __init__ that initializes the object. It is like a constructor, but the object is already created when __init__ is called.\n",
"\n",
"Instance attributes are define as self.variables. (self is the same than this in Java)."
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"#Example class declaration\n",
"class TV_Set:\n",
" def __init__(self, name):\n",
" self.name = name\n",
" self.status = 'off'\n",
"\n",
" def on(self):\n",
" self.status = 'on'\n",
"\n",
" def off(self):\n",
" self.status = 'off'"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"<__main__.TV_Set object at 0x7fa0ec1a6c50> off\n"
]
},
{
"data": {
"text/plain": [
"__main__.TV_Set"
]
},
"execution_count": 13,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"#€xample object instantiation\n",
"\n",
"my_tv = TV_Set('Samsung')\n",
"print(my_tv, my_tv.status)\n",
"type(my_tv)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Class attributes\n",
"We can also define class variables and class methods. \n",
"\n",
"Class variables are shared across all class instances. Class methods are called directly in the class. (In Java, this was defined with the keyword static)."
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0\n",
"1\n",
"2\n"
]
}
],
"source": [
"#Example class declaration\n",
"class TV_Set:\n",
" num_tvs = 0\n",
" def __init__(self, name):\n",
" self.name = name\n",
" self.status = 'off'\n",
" TV_Set.num_tvs += 1\n",
"\n",
" def on(self):\n",
" self.status = 'on'\n",
"\n",
" def off(self):\n",
" self.status = 'off'\n",
"\n",
"print(TV_Set.num_tvs)\n",
"\n",
"tv_1 = TV_Set('LG')\n",
"print(TV_Set.num_tvs)\n",
"\n",
"tv_2 = TV_Set('Samsung')\n",
"print(TV_Set.num_tvs)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Special or Magic methods\n",
"\n",
"[Special methods](https://docs.python.org/2/reference/datamodel.html#specialnames) allow programmers to customize a class. The convention for special methods is \\__method\\__.\n",
"\n",
"We have already seen a special method: \\__init\\__. Other special methods are \\__str\\__ (self) for printing) or \\__eq\\__(self, other) for comparing if two objects are equal."
]
},
{
"cell_type": "code",
"execution_count": 29,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"<__main__.Person object at 0x7fa0ec14ec88>\n"
]
}
],
"source": [
"class Person:\n",
" def __init__(self, name, age):\n",
" self.name = name\n",
" self.age = age\n",
" \n",
"p = Person('Pedro', 10)\n",
"p.age = 0\n",
"print(p)"
]
},
{
"cell_type": "code",
"execution_count": 30,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"name: Pedro, age: 0\n"
]
}
],
"source": [
"# Example __str(self)__\n",
"\n",
"class Person:\n",
" def __init__(self, name, age):\n",
" self.name = name\n",
" self.age = age\n",
" \n",
" def __str__(self):\n",
" return 'name: ' + self.name + ', ' + 'age: ' + str(self.age) # str() for converting int into string\n",
" \n",
"p = Person('Pedro', 10)\n",
"p.age = 0\n",
"print(p)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Private attributes and methods\n",
"\n",
"In Python, all methods and attributes are public. However, Python uses the following conventions\n",
"\n",
"* **Names prefixed by a single leading underscore**: (e.g. self._a, _\\_calculate()): private use. The statement import does not import objects whose name starts with an underscore. In fact, for class inheritance it has the semantics of *protected* (the subclass would have access to the method / attribute).\n",
"\n",
"* **Names prefixed by a double leading underscore** (e.g. \\_\\_calculate(), self.\\_\\_boo): used to avoid a method to be overridden by a subclass. The interpreter invokes name mangling, (inside class FooBar, \\_\\_boo becomes _FooBar\\__boo). This is not used as widely as a single leading underscore."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Instead of Getters and Setters, Python uses Properties"
]
},
{
"cell_type": "code",
"execution_count": 28,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"name: Pedro, age: -1\n"
]
}
],
"source": [
"# Now we could change the age of Pedro to a negative value\n",
"p.age = -1\n",
"print(p)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In Java, we would define age as private, and getters and setters. In Python, we can use **properties** when we want to control how they are accessed, without changing the interface."
]
},
{
"cell_type": "code",
"execution_count": 36,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"name: Pedro, age: 0\n"
]
}
],
"source": [
"class Person:\n",
" def __init__(self, name, age):\n",
" self.name = name\n",
" self.age = age\n",
" \n",
" def __str__(self):\n",
" return 'name: ' + self.name + ', ' + 'age: ' + str(self.age) # str() for converting int into string\n",
" \n",
" @property # property for getter, in this case it is not needed\n",
" def age(self):\n",
" return self._age \n",
" \n",
" @age.setter\n",
" def age(self, val):\n",
" if (val < 0):\n",
" self._age = 0 # A better alternative would be to throw an exception: raise ValueError(\"Age < 0\")\n",
" else:\n",
" self._age = val\n",
" \n",
"p = Person('Pedro', -1)\n",
"print(p)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Licence"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The notebook is freely licensed under under the [Creative Commons Attribution Share-Alike license](https://creativecommons.org/licenses/by/2.0/). \n",
"\n",
"© 2015 Carlos A. Iglesias, Universidad Politécnica de Madrid."
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.5.1"
}
},
"nbformat": 4,
"nbformat_minor": 0
}

@ -0,0 +1,304 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"![](http://www.upm.es/sfs/Rectorado/Gabinete%20del%20Rector/Logos/UPM/EscPolitecnica/EscUpmPolit_p.gif \"UPM\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Course Notes for Learning Intelligent Systems"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Department of Telematic Engineering Systems, Universidad Politécnica de Madrid, © 2015 Carlos A. Iglesias"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Errors and Exceptions"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Errors\n",
"\n",
"Errors (or syntax errors) are errors because the syntax is incorrect."
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"collapsed": false
},
"outputs": [
{
"ename": "SyntaxError",
"evalue": "invalid syntax (<ipython-input-1-16b482c78ccd>, line 2)",
"output_type": "error",
"traceback": [
"\u001b[1;36m File \u001b[1;32m\"<ipython-input-1-16b482c78ccd>\"\u001b[1;36m, line \u001b[1;32m2\u001b[0m\n\u001b[1;33m while True\u001b[0m\n\u001b[1;37m ^\u001b[0m\n\u001b[1;31mSyntaxError\u001b[0m\u001b[1;31m:\u001b[0m invalid syntax\n"
]
}
],
"source": [
"# Example SyntaxError - missing semicolon in while\n",
"while True\n",
" print \"hi\""
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Exceptions\n",
"Even when the syntax is correct, we can have other types of errors."
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"collapsed": false
},
"outputs": [
{
"ename": "TypeError",
"evalue": "unsupported operand type(s) for +: 'int' and 'str'",
"output_type": "error",
"traceback": [
"\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)",
"\u001b[1;32m<ipython-input-2-fb8fe04af7b6>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m()\u001b[0m\n\u001b[0;32m 1\u001b[0m \u001b[1;31m# Example TypeError - wrong use of '+' with different types\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 2\u001b[1;33m \u001b[1;36m3\u001b[0m \u001b[1;33m+\u001b[0m \u001b[1;34m'a'\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[1;31mTypeError\u001b[0m: unsupported operand type(s) for +: 'int' and 'str'"
]
}
],
"source": [
"# Example TypeError - wrong use of '+' with different types\n",
"3 + 'a'"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"collapsed": false,
"scrolled": true
},
"outputs": [
{
"ename": "NameError",
"evalue": "name 'a' is not defined",
"output_type": "error",
"traceback": [
"\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[1;31mNameError\u001b[0m Traceback (most recent call last)",
"\u001b[1;32m<ipython-input-3-82179588c5b9>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m()\u001b[0m\n\u001b[0;32m 1\u001b[0m \u001b[1;31m# Example NameError: variable not defined\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 2\u001b[1;33m \u001b[0ma\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[1;31mNameError\u001b[0m: name 'a' is not defined"
]
}
],
"source": [
"# Example NameError: variable not defined\n",
"a \n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Exceptions can be handled with the statement **try-except-else-finally**. \n",
"\n",
"* **try**: code block when an exception can occur\n",
"* **except**: code block executed if the exception ocurrs (catches the exception)\n",
"* **else**: (optional) code block executed if no exception occurs\n",
"* **finally**: (optional) code block executed always (both if there is an exception or not)"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Please enter a number: a\n",
"Oops! That was no valid number. Try again...\n",
"Please enter a number: 1\n"
]
}
],
"source": [
"# Example\n",
"# Try to enter a wrong input (e.g. a) and then a number (e.g. 0)\n",
"while True:\n",
" try:\n",
" num = int(input(\"Please enter a number: \"))\n",
" break\n",
" except ValueError:\n",
" print(\"Oops! That was no valid number. Try again...\")"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Please enter a number: a\n",
"Oops! That was no valid number. Try again...\n",
"End of input\n",
"Please enter a number: 1\n",
"End of input\n"
]
}
],
"source": [
"# Example with finally\n",
"while True:\n",
" try:\n",
" num = int(input(\"Please enter a number: \"))\n",
" break\n",
" except ValueError:\n",
" print(\"Oops! That was no valid number. Try again...\")\n",
" finally:\n",
" print(\"End of input\")"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Please enter a number: a\n",
"Oops! That was no valid number.\n",
"Number entered\n",
"Please enter a number: 1\n",
"No exception\n",
"Number entered\n"
]
}
],
"source": [
"# Example with else and finally\n",
"while True:\n",
" try:\n",
" num = int(input(\"Please enter a number: \"))\n",
" except ValueError:\n",
" print(\"Oops! That was no valid number.\")\n",
" continue\n",
" else:\n",
" print(\"No exception\")\n",
" break\n",
" finally:\n",
" print(\"Number entered\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Exception can be thrown with 'raise'"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"collapsed": false
},
"outputs": [
{
"ename": "TypeError",
"evalue": "Both arguments should be numbers or strings",
"output_type": "error",
"traceback": [
"\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)",
"\u001b[1;32m<ipython-input-5-1e4048e7e923>\u001b[0m in \u001b[0;36madd\u001b[1;34m(a, b)\u001b[0m\n\u001b[0;32m 2\u001b[0m \u001b[1;32mtry\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 3\u001b[1;33m \u001b[1;32mreturn\u001b[0m \u001b[0ma\u001b[0m \u001b[1;33m+\u001b[0m \u001b[0mb\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 4\u001b[0m \u001b[1;32mexcept\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
"\u001b[1;31mTypeError\u001b[0m: unsupported operand type(s) for +: 'int' and 'str'",
"\nDuring handling of the above exception, another exception occurred:\n",
"\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)",
"\u001b[1;32m<ipython-input-5-1e4048e7e923>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m()\u001b[0m\n\u001b[0;32m 5\u001b[0m \u001b[1;32mraise\u001b[0m \u001b[0mTypeError\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"Both arguments should be numbers or strings\"\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 6\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 7\u001b[1;33m \u001b[0madd\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;36m3\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;34m'a'\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[1;32m<ipython-input-5-1e4048e7e923>\u001b[0m in \u001b[0;36madd\u001b[1;34m(a, b)\u001b[0m\n\u001b[0;32m 3\u001b[0m \u001b[1;32mreturn\u001b[0m \u001b[0ma\u001b[0m \u001b[1;33m+\u001b[0m \u001b[0mb\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 4\u001b[0m \u001b[1;32mexcept\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 5\u001b[1;33m \u001b[1;32mraise\u001b[0m \u001b[0mTypeError\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"Both arguments should be numbers or strings\"\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 6\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 7\u001b[0m \u001b[0madd\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;36m3\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;34m'a'\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
"\u001b[1;31mTypeError\u001b[0m: Both arguments should be numbers or strings"
]
}
],
"source": [
"def add(a, b):\n",
" try:\n",
" return a + b\n",
" except:\n",
" raise TypeError(\"Both arguments should be numbers or strings\")\n",
" \n",
"add(3, 'a')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Licence"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The notebook is freely licensed under under the [Creative Commons Attribution Share-Alike license](https://creativecommons.org/licenses/by/2.0/). \n",
"\n",
"© 2015 Carlos A. Iglesias, Universidad Politécnica de Madrid."
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.5.1"
}
},
"nbformat": 4,
"nbformat_minor": 0
}

@ -0,0 +1,187 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"![](http://www.upm.es/sfs/Rectorado/Gabinete%20del%20Rector/Logos/UPM/EscPolitecnica/EscUpmPolit_p.gif \"UPM\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Course Notes for Learning Intelligent Systems"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Department of Telematic Engineering Systems, Universidad Politécnica de Madrid, © 2015 Carlos A. Iglesias"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Modules and Packages\n",
"\n",
"*Modules* contains definitions and objects that can be reused in other programmes.\n",
"\n",
"*Packages* contain subpackages of modules. They are directories and provide the namespace for modules.\n",
"\n",
"For example, let's have this package sound, a subpackage effects and the modules echo and surround:\n",
"\n",
"<code>\n",
"babel/\n",
" messages/\n",
" \\_\\_init\\_\\_.py\n",
" plurals.py\n",
" catalog.py\n",
"</code>\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {
"collapsed": false
},
"outputs": [
{
"ename": "NameError",
"evalue": "name 'plurals' is not defined",
"output_type": "error",
"traceback": [
"\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[1;31mNameError\u001b[0m Traceback (most recent call last)",
"\u001b[1;32m<ipython-input-9-1ca6b7751408>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m()\u001b[0m\n\u001b[0;32m 1\u001b[0m \u001b[1;31m# We can import the module plural with import\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 2\u001b[0m \u001b[1;32mimport\u001b[0m \u001b[0mbabel\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mmessages\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mplurals\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 3\u001b[1;33m \u001b[0mplurals\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mget_plural\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[1;31mNameError\u001b[0m: name 'plurals' is not defined"
]
}
],
"source": [
"# We can import the module plural with import, but we should use the full name\n",
"import babel.messages.plurals\n",
"plurals.get_plural()"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"(2, '(n != 1)')"
]
},
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import babel.messages.plurals\n",
"babel.messages.plurals.get_plural()"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"(2, '(n != 1)')"
]
},
"execution_count": 12,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"from babel.messages import plurals # with from-import, we can use the short name\n",
"plurals.get_plural()"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"(2, '(n != 1)')"
]
},
"execution_count": 14,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"from babel.messages.plurals import get_plural # now we can use directly get_plural()\n",
"get_plural()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"To write a module, it is just needed to include the code in a file ended with \".py\" and the name of the file is the name of the module.\n",
"\n",
"Packages are directories that should have a file \\_\\_.init\\_\\_.py, that can be an empty file or contain initialization code."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Licence"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The notebook is freely licensed under under the [Creative Commons Attribution Share-Alike license](https://creativecommons.org/licenses/by/2.0/). \n",
"\n",
"© 2015 Carlos A. Iglesias, Universidad Politécnica de Madrid."
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.5.1"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
Loading…
Cancel
Save