{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# if, else, and elif" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Stay Home'" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "rain = True\n", "\n", "if rain is True:\n", " agenda = 'Stay Home'\n", " \n", "agenda" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "def percentage(a, b):\n", " if b == 0:\n", " return None\n", " \n", " return round(a/b, 2)" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0.1" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "percentage(10, 100)" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [], "source": [ "percentage(1, 0)" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "I don't know you...\n" ] } ], "source": [ "name = 'Adrian'\n", "\n", "if name == 'Annie':\n", " print('Hello Annie!')\n", "else:\n", " print(\"I don't know you...\")" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hey, I know you!\n" ] } ], "source": [ "if name in {'Adrian', 'Annie'}:\n", " print('Hey, I know you!')\n", "\n", "elif name in {'Agnus', 'Angela'}:\n", " print(\"Hi! I thing we've met somewhere...\")\n", "\n", "elif name in {'Boris', 'Brunhilde'} :\n", " # don't talk with them\n", " pass # pass can be used in code when sintaxis requires some code, but none is needed\n", "\n", "else:\n", " print(\"I don't think I know you...\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Inline `if` statements" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Adrian'" ] }, "execution_count": 20, "metadata": {}, "output_type": "execute_result" } ], "source": [ "name = name or 'Sigizmund'\n", "name" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Sigizmund'" ] }, "execution_count": 21, "metadata": {}, "output_type": "execute_result" } ], "source": [ "name = 0\n", "name = name or 'Sigizmund'\n", "name" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0" ] }, "execution_count": 23, "metadata": {}, "output_type": "execute_result" } ], "source": [ "name = 0\n", "name = name if name is not None else 'Sigizmund'\n", "name" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Using `if` in comprehensions" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['Peter', 'Josephine']" ] }, "execution_count": 25, "metadata": {}, "output_type": "execute_result" } ], "source": [ "characters = [\n", " {'name': 'Peter', \"surname\": 'Rabbit'},\n", " {'name': 'Josephine', 'surname': 'Rabbit'},\n", " {'name': 'Michael', 'surname': 'McGregor'} \n", "]\n", "\n", "rabbits = [el['name'] for el in characters if el['surname'] == 'Rabbit']\n", "rabbits" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Loops" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## `For` loop" ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0\n", "1\n", "2\n" ] } ], "source": [ "for i in range(3):\n", " print(i)" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "J\n", "a\n", "c\n", "k\n" ] } ], "source": [ "for char in 'Jack':\n", " print(char)" ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "name : Jim\n", "surname : Hockins\n" ] } ], "source": [ "person = {\n", " 'name':'Jim',\n", " 'surname':'Hockins'\n", "}\n", "\n", "for k, v in person.items():\n", " print(k, ':', v)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Itertools" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Cycle" ] }, { "cell_type": "code", "execution_count": 31, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1 red\n", "2 green\n", "3 blue\n", "4 red\n", "5 green\n" ] } ], "source": [ "from itertools import cycle\n", "colors, categories = cycle(('red', 'green', 'blue')), (1, 2, 3, 4, 5)\n", "\n", "\n", "for cat, color in zip(categories, colors):\n", " print(cat, color)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Groupby" ] }, { "cell_type": "code", "execution_count": 32, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Rabbit\n", " Peter\n", " Josephine\n", "McGregor\n", " Michael\n" ] } ], "source": [ "from itertools import groupby\n", "\n", "characters = [\n", " {'name': 'Peter', \"surname\": 'Rabbit'},\n", " {'name': 'Josephine', 'surname': 'Rabbit'},\n", " {'name': 'Michael', 'surname': 'McGregor'} \n", "]\n", "\n", "for group_name, group in groupby(characters, lambda x: x['surname']):\n", " print(group_name)\n", " for el in group:\n", " print(' ', el['name'])\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Product" ] }, { "cell_type": "code", "execution_count": 33, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 33, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from itertools import product\n", "w1, w2, w3, w4 = 'Hello the wonderful world!'.split() # splits by the whitespace by default\n", "\n", "values1 = []\n", "for el1 in w1:\n", " for el2 in w2:\n", " for el3 in w3:\n", " for el4 in w4:\n", " values1.append(el1 + el2 + el3 + el4)\n", "\n", "\n", "# OR\n", "values2 = []\n", "for el1, el2, el3, el4 in product(w1, w2, w3, w4):\n", " values2.append(el1 + el2 + el3 + el4)\n", "\n", "values1 == values2" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Enumeration" ] }, { "cell_type": "code", "execution_count": 37, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1. name: Jim\n", "2. surname: Hockins\n" ] } ], "source": [ "# here, 1 defines starting index\n", "for i, (k, v) in enumerate(person.items(), 1):\n", " print(f'{i}. {k}: {v}')\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## `While` loop" ] }, { "cell_type": "code", "execution_count": 38, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0\n", "1\n", "2\n", "3\n", "4\n" ] } ], "source": [ "counter = 0\n", "while counter < 5:\n", " print(counter)\n", " counter += 1" ] }, { "cell_type": "code", "execution_count": 41, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Below minimum!\n", "Value is: 3, Samples took: 18\n" ] } ], "source": [ "from random import randint # built-in random values generator\n", "counter = 0\n", "minimum = 10\n", "\n", "while True:\n", " value = randint(1, 100)\n", " if value < minimum:\n", " print('Below minimum!')\n", " break\n", "\n", " counter +=1\n", "\n", "print(f'Value is: {value}, Samples took: {counter}')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Additional functionality - break and continue\n" ] }, { "cell_type": "code", "execution_count": 42, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "D\n", "a\n" ] } ], "source": [ "for letter in \"Data\":\n", " if letter == 't':\n", " break\n", " print(letter)" ] }, { "cell_type": "code", "execution_count": 43, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "D\n", "a\n", "a\n" ] } ], "source": [ "for letter in \"Data\":\n", " if letter == 't':\n", " continue\n", " print(letter)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Try/except/finally" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Exceptions" ] }, { "cell_type": "code", "execution_count": 49, "metadata": {}, "outputs": [], "source": [ "def _check_raise(inst, type_, text=None):\n", " text = text if text is not None else f'Wrong value: requires {type} format, got {type(inst)}'\n", "\n", " if not isinstance(inst, type_):\n", " raise ValueError(text)" ] }, { "cell_type": "code", "execution_count": 45, "metadata": {}, "outputs": [], "source": [ "_check_raise('Hello', str)" ] }, { "cell_type": "code", "execution_count": 50, "metadata": {}, "outputs": [ { "ename": "ValueError", "evalue": "Wrong value: requires format, got ", "output_type": "error", "traceback": [ "\u001b[0;31m--------------------------------------------------\u001b[0m", "\u001b[0;31mValueError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0m_check_raise\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'Hello'\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mint\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;32m\u001b[0m in \u001b[0;36m_check_raise\u001b[0;34m(inst, type_, text)\u001b[0m\n\u001b[1;32m 3\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 4\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0;32mnot\u001b[0m \u001b[0misinstance\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0minst\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mtype_\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 5\u001b[0;31m \u001b[0;32mraise\u001b[0m \u001b[0mValueError\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mtext\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mValueError\u001b[0m: Wrong value: requires format, got " ] } ], "source": [ "_check_raise('Hello', int)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Try/Finally" ] }, { "cell_type": "code", "execution_count": 51, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "something is wrong!\n" ] }, { "ename": "ZeroDivisionError", "evalue": "division by zero", "output_type": "error", "traceback": [ "\u001b[0;31m--------------------------------------------------\u001b[0m", "\u001b[0;31mZeroDivisionError\u001b[0mTraceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;32mtry\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0mresult\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;36m1\u001b[0m \u001b[0;34m/\u001b[0m \u001b[0;36m0\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 3\u001b[0m \u001b[0;32mfinally\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 4\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'something is wrong!'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", "\u001b[0;31mZeroDivisionError\u001b[0m: division by zero" ] } ], "source": [ "try:\n", " result = 1 / 0\n", "finally:\n", " print('something is wrong!')\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Try/except" ] }, { "cell_type": "code", "execution_count": 53, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "something is wrong!\n" ] } ], "source": [ "try:\n", " result = 1 / 0\n", "except ZeroDivisionError:\n", " print('something is wrong!')\n" ] }, { "cell_type": "code", "execution_count": 59, "metadata": {}, "outputs": [], "source": [ "import warnings \n", "# built-in library that helps warning people - similar to exceptions, but won't halt code,\n", "# you can also set up filter for different warning types\n", "\n", "def percentage(value, total):\n", " try:\n", " return 100*(value / total)\n", "\n", " except ZeroDivisionError:\n", " warnings.warn('Total cannot be zero!')\n", "\n", " except (TypeError, KeyError) as e:\n", " # Keyerror here would never occur - just used it for example\n", " warnings.warn(f'Something with the wrong: {e}')\n", "\n", " except Exception as e:\n", " raise Exception(value, total, e)\n", "\n", " finally:\n", " print('Anyhow, this function was executed!')" ] }, { "cell_type": "code", "execution_count": 57, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Anyhow, this function was executed!\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "/Users/philippk/anaconda3/envs/py36/lib/python3.6/site-packages/ipykernel_launcher.py:10: UserWarning: Total cannot be zero!\n", " # Remove the CWD from sys.path while we load stuff.\n" ] } ], "source": [ "percentage(10, 0)" ] }, { "cell_type": "code", "execution_count": 60, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Anyhow, this function was executed!\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "/Users/philippk/anaconda3/envs/py36/lib/python3.6/site-packages/ipykernel_launcher.py:14: UserWarning: Something with the wrong: unsupported operand type(s) for /: 'str' and 'str'\n", " \n" ] } ], "source": [ "percentage('Hello', 'world')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# `With` statement" ] }, { "cell_type": "code", "execution_count": 62, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello\n", "World!\n" ] } ], "source": [ "with open('./text_file.txt', 'r') as file:\n", " data = file.read()\n", "\n", "print(data)" ] }, { "cell_type": "code", "execution_count": 63, "metadata": {}, "outputs": [], "source": [ "try:\n", " file = open('./text_file.txt', 'r').__enter__()\n", " data = file.read() \n", "finally:\n", " file.__exit__()" ] }, { "cell_type": "code", "execution_count": 64, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Hello\\nWorld!'" ] }, "execution_count": 64, "metadata": {}, "output_type": "execute_result" } ], "source": [ "data" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "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.6.5" } }, "nbformat": 4, "nbformat_minor": 2 }