1
0
mirror of https://github.com/gsi-upm/sitc synced 2024-11-16 19:42:28 +00:00
sitc/python/1_5_ControlFlow.ipynb
Carlos A. Iglesias 842b6307f1 Updated notebooks
2019-03-06 17:46:12 +01:00

457 lines
9.5 KiB
Plaintext

{
"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, © 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": {},
"source": [
"## 1. Conditional statements: if, elif, else"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"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": null,
"metadata": {},
"outputs": [],
"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": null,
"metadata": {},
"outputs": [],
"source": [
"# Only one branch\n",
"if x <= 5:\n",
" print(\"Too small\")\n",
"else:\n",
" print(\"Too big\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"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": null,
"metadata": {},
"outputs": [],
"source": [
"# for with ranges\n",
"for i in range(10): \n",
" print(i)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# for with lists\n",
"l = [1, 2, 3, 4]\n",
"for i in l:\n",
" print(i)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# for with tuples\n",
"t = (1, 'a', 'b')\n",
"for i in t:\n",
" print(i)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"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": null,
"metadata": {},
"outputs": [],
"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": null,
"metadata": {},
"outputs": [],
"source": [
"x = 5\n",
"while x > 1:\n",
" print(x)\n",
" x -= 1 # Python does not have x--"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Else is optional\n",
"x = 2\n",
"while x < 5: \n",
" print(x)\n",
" x += 1"
]
},
{
"cell_type": "markdown",
"metadata": {},
"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": null,
"metadata": {},
"outputs": [],
"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": null,
"metadata": {},
"outputs": [],
"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": null,
"metadata": {},
"outputs": [],
"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": null,
"metadata": {},
"outputs": [],
"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": null,
"metadata": {},
"outputs": [],
"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": null,
"metadata": {},
"outputs": [],
"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": null,
"metadata": {},
"outputs": [],
"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": null,
"metadata": {},
"outputs": [],
"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": null,
"metadata": {},
"outputs": [],
"source": [
"# list = {x² : x in {0 ... 9}}\n",
"list = [x*x for x in range(10)]\n",
"list"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"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",
"© 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.7.1"
},
"latex_envs": {
"LaTeX_envs_menu_present": true,
"autocomplete": true,
"bibliofile": "biblio.bib",
"cite_by": "apalike",
"current_citInitial": 1,
"eqLabelWithNumbers": true,
"eqNumInitial": 1,
"hotkeys": {
"equation": "Ctrl-E",
"itemize": "Ctrl-I"
},
"labels_anchors": false,
"latex_user_defs": false,
"report_style_numbering": false,
"user_envs_cfg": false
}
},
"nbformat": 4,
"nbformat_minor": 1
}