{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Das ``with`` Statement" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "def f():\n", " l = [1, 2, 3]" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "f()" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "def f():\n", " try:\n", " openfile = open('/etc/passwd')\n", " except ValueError as e:\n", " # hanlde err\n", " raise\n", " finally:\n", " openfile.close()\n", "f()" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": [ "def f():\n", " with open('/etc/passwd') as openfile:\n", " # do soemthing with openfile\n", " \n", " # no closing necessary\n", " pass # Python requires me to write at least one syntactically correct statement" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# ``import zipfile``" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [], "source": [ "import zipfile" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [], "source": [ "zf = zipfile.ZipFile('demo.zip')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Read Contents ..." ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['tmp/zipdemo/', 'tmp/zipdemo/group', 'tmp/zipdemo/passwd']" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "zf.namelist()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Extract One Member" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'/tmp/my-extraction-directory/tmp/zipdemo/group'" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "extracted_name = zf.extract(member='tmp/zipdemo/group', path='/tmp/my-extraction-directory')\n", "extracted_name" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## All in One, Using ``with``" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['tmp/zipdemo/', 'tmp/zipdemo/group', 'tmp/zipdemo/passwd']\n", "/tmp/my-extraction-directory/tmp/zipdemo/group\n" ] } ], "source": [ "with zipfile.ZipFile('demo.zip') as zf:\n", " print(zf.namelist())\n", " print(zf.extract(member='tmp/zipdemo/group', path='/tmp/my-extraction-directory'))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Classes" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Question 31**\n", "\n", "Select the true statements:\n", "\n", "(select all that apply)\n", "\n", "* A. The ``class`` keyword marks the beginning of the class definition\n", "* B. An object cannot contain any references to other objects\n", "* C. A class may define an object\n", "* D. A constructor is used to instantiate an object\n", "* E. An object variable is a variable that is stored separately in every object" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [], "source": [ "class Person:\n", " pass" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [], "source": [ "p = Person() # instantiation\n", "p.first = 'Joerg'\n", "p.last = 'Faschingbauer'\n", "p.address = 'Prankergasse 33, 8020 Graz'" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [], "source": [ "class Person:\n", " def __init__(self, first, last, address):\n", " self.first = first\n", " self.last = last\n", " self.address = address\n", "p = Person('Joerg', 'Faschingbauer', 'Prankergasse 33, 8020 Graz') # instantiation" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Joerg'" ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "p.first" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "isinstance(p, Person)" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "isinstance(p, str)" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'first': 'Joerg',\n", " 'last': 'Faschingbauer',\n", " 'address': 'Prankergasse 33, 8020 Graz'}" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "p.__dict__" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Inheritance" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Question 32**\n", "\n", "Select the true statements:\n", "\n", "(select all that apply)\n", "\n", "* A. Inheritance means passing attributes and methods from a superclass to a subclass\n", "* B. ``issubclass(class1, class2)`` is an example of a function that returns ``True`` if ``class2`` is a subclass of ``class1``\n", "* C. Multiple inheritance means that a class has more than one superclass\n", "* D. Polymorphism is the situation in which a subclass is able to modify its superclass behavior\n", "* E. A single inheritance is always more difficult to maintain than a multiple inheritance" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [], "source": [ "class Employee(Person):\n", " def __init__(self, first, last, address, salary):\n", " self.salary = salary\n", " super().__init__(first, last, address)" ] }, { "cell_type": "code", "execution_count": 18, "metadata": { "scrolled": true }, "outputs": [], "source": [ "e = Employee('Selina', 'Orgl', 'Somewhere 666, 8010 Graz', 2000) # instantiation" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Selina'" ] }, "execution_count": 19, "metadata": {}, "output_type": "execute_result" } ], "source": [ "e.first" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "2000" ] }, "execution_count": 20, "metadata": {}, "output_type": "execute_result" } ], "source": [ "e.salary" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'salary': 2000,\n", " 'first': 'Selina',\n", " 'last': 'Orgl',\n", " 'address': 'Somewhere 666, 8010 Graz'}" ] }, "execution_count": 21, "metadata": {}, "output_type": "execute_result" } ], "source": [ "e.__dict__" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 22, "metadata": {}, "output_type": "execute_result" } ], "source": [ "isinstance(e, Employee)" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 23, "metadata": {}, "output_type": "execute_result" } ], "source": [ "isinstance(e, Person)" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 24, "metadata": {}, "output_type": "execute_result" } ], "source": [ "issubclass(Employee, Person)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Functionality: Methods" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [], "source": [ "import time\n", "\n", "class Person:\n", " def __init__(self, first, last, address):\n", " self.first = first\n", " self.last = last\n", " self.address = address\n", " self.birth = time.time()\n", " def die(self):\n", " self.death = time.time()\n", " def lifetime(self):\n", " return self.death - self.birth" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Employee inherits everything but salary" ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [], "source": [ "class Employee(Person):\n", " def __init__(self, first, last, address, salary):\n", " self.salary = salary\n", " super().__init__(first, last, address)" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [], "source": [ "joerg = Person('Joerg', 'Faschingbauer', 'Prankergasse 33, 8020 Graz')" ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1622102062.4778333" ] }, "execution_count": 28, "metadata": {}, "output_type": "execute_result" } ], "source": [ "joerg.birth" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "joerg.die()\n", "joerg.death" ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0.019427776336669922" ] }, "execution_count": 29, "metadata": {}, "output_type": "execute_result" } ], "source": [ "joerg.die()\n", "joerg.lifetime()" ] }, { "cell_type": "code", "execution_count": 30, "metadata": { "scrolled": true }, "outputs": [], "source": [ "selina = Employee('Selina', 'Orgl', 'Somewhere 666, 8010 Graz', 2000)" ] }, { "cell_type": "code", "execution_count": 31, "metadata": { "scrolled": true }, "outputs": [ { "data": { "text/plain": [ "0.009679079055786133" ] }, "execution_count": 31, "metadata": {}, "output_type": "execute_result" } ], "source": [ "selina.die()\n", "selina.lifetime()" ] }, { "cell_type": "code", "execution_count": 32, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "__main__.Employee" ] }, "execution_count": 32, "metadata": {}, "output_type": "execute_result" } ], "source": [ "daniel = Employee('Daniel', 'Ortner', 'Blah 42', 1000)\n", "type(daniel)" ] }, { "cell_type": "code", "execution_count": 33, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 33, "metadata": {}, "output_type": "execute_result" } ], "source": [ "isinstance(daniel, Employee)" ] }, { "cell_type": "code", "execution_count": 34, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 34, "metadata": {}, "output_type": "execute_result" } ], "source": [ "isinstance(daniel, Person)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Class Attributes vs. Instance Attributes (*not* Variables)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Instance Attributes" ] }, { "cell_type": "code", "execution_count": 35, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Daniel'" ] }, "execution_count": 35, "metadata": {}, "output_type": "execute_result" } ], "source": [ "daniel.first" ] }, { "cell_type": "code", "execution_count": 36, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Selina'" ] }, "execution_count": 36, "metadata": {}, "output_type": "execute_result" } ], "source": [ "selina.first" ] }, { "cell_type": "code", "execution_count": 37, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Joerg'" ] }, "execution_count": 37, "metadata": {}, "output_type": "execute_result" } ], "source": [ "joerg.first" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Class Attributes" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "How many Employees exist?" ] }, { "cell_type": "code", "execution_count": 38, "metadata": {}, "outputs": [], "source": [ "class Employee(Person):\n", " num_employees = 0 # class attribute \n", " def __init__(self, first, last, address, salary):\n", " self.salary = salary\n", " Employee.num_employees += 1 # class attribute can be accessed via class Employee\n", " super().__init__(first, last, address)\n", " def die(self):\n", " '''Acts like Person.die(), and in addition keeps track of num. employees'''\n", " self.num_employees -= 1 # class attributes can be access via any object of the class\n", " super().die()" ] }, { "cell_type": "code", "execution_count": 39, "metadata": {}, "outputs": [], "source": [ "selina = Employee('Selina', 'Orgl', 'Somewhere 666, 8010 Graz', 2000)\n", "daniel = Employee('Daniel', 'Ortner', 'Blah 42', 1000)" ] }, { "cell_type": "code", "execution_count": 40, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "2" ] }, "execution_count": 40, "metadata": {}, "output_type": "execute_result" } ], "source": [ "Employee.num_employees" ] }, { "cell_type": "code", "execution_count": 41, "metadata": {}, "outputs": [], "source": [ "selina.die()" ] }, { "cell_type": "code", "execution_count": 42, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "2" ] }, "execution_count": 42, "metadata": {}, "output_type": "execute_result" } ], "source": [ "Employee.num_employees" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Public, Protected, Private" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\"Private\" is actually only name mangling" ] }, { "cell_type": "code", "execution_count": 43, "metadata": {}, "outputs": [], "source": [ "class Person:\n", " def __init__(self, first, last, address):\n", " self.__first = first\n", " self.__last = last\n", " self.__address = address\n", "p = Person('Joerg', 'Faschingbauer', 'Prankergasse 33, 8020 Graz')" ] }, { "cell_type": "code", "execution_count": 44, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "'Person' object has no attribute '__first'\n" ] } ], "source": [ "try:\n", " p.__first\n", "except Exception as e:\n", " print(e)" ] }, { "cell_type": "code", "execution_count": 45, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'_Person__first': 'Joerg',\n", " '_Person__last': 'Faschingbauer',\n", " '_Person__address': 'Prankergasse 33, 8020 Graz'}" ] }, "execution_count": 45, "metadata": {}, "output_type": "execute_result" } ], "source": [ "p.__dict__" ] }, { "cell_type": "code", "execution_count": 46, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Joerg'" ] }, "execution_count": 46, "metadata": {}, "output_type": "execute_result" } ], "source": [ "p._Person__first" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This is maybe \"Protected\"?" ] }, { "cell_type": "code", "execution_count": 47, "metadata": {}, "outputs": [], "source": [ "class Person:\n", " def __init__(self, first, last, address):\n", " self._first = first\n", " self._last = last\n", " self._address = address\n", "p = Person('Joerg', 'Faschingbauer', 'Prankergasse 33, 8020 Graz')" ] }, { "cell_type": "code", "execution_count": 48, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'_first': 'Joerg',\n", " '_last': 'Faschingbauer',\n", " '_address': 'Prankergasse 33, 8020 Graz'}" ] }, "execution_count": 48, "metadata": {}, "output_type": "execute_result" } ], "source": [ "p.__dict__" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Properties" ] }, { "cell_type": "code", "execution_count": 49, "metadata": {}, "outputs": [], "source": [ "class Person:\n", " def __init__(self, first, last, address):\n", " self._first = first\n", " self._last = last\n", " self._address = address\n", " @property\n", " def first(self):\n", " return self._first\n", " @first.setter\n", " def first(self, name):\n", " 'Only allow Persons with firstname Joerg to be renamed'\n", " if self._first == 'Joerg':\n", " self._first = name\n", " else:\n", " raise RuntimeError('nix rename')\n", "p = Person('Joerg', 'Faschingbauer', 'Prankergasse 33, 8020 Graz')" ] }, { "cell_type": "code", "execution_count": 50, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Joerg'" ] }, "execution_count": 50, "metadata": {}, "output_type": "execute_result" } ], "source": [ "p.first" ] }, { "cell_type": "code", "execution_count": 51, "metadata": {}, "outputs": [], "source": [ "p.first = 'Eugenie'" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Functions, Positional and Keyword Arguments" ] }, { "cell_type": "code", "execution_count": 52, "metadata": {}, "outputs": [], "source": [ "def velocity(length_m, time_s, do_debug):\n", " val = length_m/time_s\n", " if do_debug:\n", " print('velocity=', val)\n", " return val" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Positional Arguments" ] }, { "cell_type": "code", "execution_count": 53, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "velocity= 0.5\n" ] }, { "data": { "text/plain": [ "0.5" ] }, "execution_count": 53, "metadata": {}, "output_type": "execute_result" } ], "source": [ "velocity(5, 10, True)" ] }, { "cell_type": "code", "execution_count": 54, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "2.0" ] }, "execution_count": 54, "metadata": {}, "output_type": "execute_result" } ], "source": [ "velocity(10, 5, False)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Keyword Arguments" ] }, { "cell_type": "code", "execution_count": 55, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0.5" ] }, "execution_count": 55, "metadata": {}, "output_type": "execute_result" } ], "source": [ "velocity(time_s=10, length_m=5, do_debug=False)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Mixing Positional and Keyword Arguments" ] }, { "cell_type": "code", "execution_count": 56, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "velocity= 0.5\n" ] }, { "data": { "text/plain": [ "0.5" ] }, "execution_count": 56, "metadata": {}, "output_type": "execute_result" } ], "source": [ "velocity(5, do_debug=True, time_s=10) # keyword args only after positional" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# The ``range()`` Function" ] }, { "cell_type": "code", "execution_count": 57, "metadata": {}, "outputs": [], "source": [ "row = ['Language', 'bloh', '', '666', '']" ] }, { "cell_type": "code", "execution_count": 58, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "5" ] }, "execution_count": 58, "metadata": {}, "output_type": "execute_result" } ], "source": [ "len(row)" ] }, { "cell_type": "code", "execution_count": 59, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2\n", "3\n", "4\n" ] } ], "source": [ "for i in range(2, len(row)):\n", " print(i)" ] }, { "cell_type": "raw", "metadata": {}, "source": [ "Was ist ``range()`` ueberhaupt???" ] }, { "cell_type": "code", "execution_count": 60, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "range(0, 3)" ] }, "execution_count": 60, "metadata": {}, "output_type": "execute_result" } ], "source": [ "r = range(3) # same as range(0,3)\n", "r" ] }, { "cell_type": "code", "execution_count": 61, "metadata": {}, "outputs": [], "source": [ "it = iter(r)" ] }, { "cell_type": "code", "execution_count": 62, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0" ] }, "execution_count": 62, "metadata": {}, "output_type": "execute_result" } ], "source": [ "next(it)" ] }, { "cell_type": "code", "execution_count": 63, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 63, "metadata": {}, "output_type": "execute_result" } ], "source": [ "next(it)" ] }, { "cell_type": "code", "execution_count": 64, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "2" ] }, "execution_count": 64, "metadata": {}, "output_type": "execute_result" } ], "source": [ "next(it)" ] }, { "cell_type": "code", "execution_count": 65, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "there is nothing more\n" ] } ], "source": [ "try:\n", " next(it)\n", "except StopIteration:\n", " print('there is nothing more')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This is exactly the same a using the ``for`` loop to iterate over a range (or anything that is iterable)" ] }, { "cell_type": "code", "execution_count": 66, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0\n", "1\n", "2\n" ] } ], "source": [ "for element in range(3):\n", " print(element)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Functional Programming, Iteration, ``yield``, ``map()``, ``filter()``, ..." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## ``map()``" ] }, { "cell_type": "code", "execution_count": 67, "metadata": {}, "outputs": [], "source": [ "l = ['1.2', '3.4', '666.42']" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Convert strings to floats:" ] }, { "cell_type": "code", "execution_count": 68, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1.2, 3.4, 666.42]" ] }, "execution_count": 68, "metadata": {}, "output_type": "execute_result" } ], "source": [ "l_float = []\n", "for element in l:\n", " l_float.append(float(element))\n", "l_float" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Do the same using a list comprehension" ] }, { "cell_type": "code", "execution_count": 69, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1.2, 3.4, 666.42]" ] }, "execution_count": 69, "metadata": {}, "output_type": "execute_result" } ], "source": [ "l_float = [float(element) for element in l]\n", "l_float" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Do the same using ``map()``" ] }, { "cell_type": "code", "execution_count": 70, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1.2\n", "3.4\n", "666.42\n" ] } ], "source": [ "l_float = map(float, l)\n", "for el in l_float:\n", " print(el)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Do the same using a generator expression" ] }, { "cell_type": "code", "execution_count": 71, "metadata": {}, "outputs": [ { "data": { "text/plain": [ " at 0x7fd9881b04a0>" ] }, "execution_count": 71, "metadata": {}, "output_type": "execute_result" } ], "source": [ "l_float = (float(element) for element in l)\n", "l_float" ] }, { "cell_type": "code", "execution_count": 72, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1.2\n", "3.4\n", "666.42\n" ] } ], "source": [ "for el in l_float:\n", " print(el)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Iterable" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "``list`` is iterable" ] }, { "cell_type": "code", "execution_count": 73, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0\n", "1\n", "2\n" ] } ], "source": [ "l = [0, 1, 2]\n", "for element in l:\n", " print(element)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "``str`` is iterable" ] }, { "cell_type": "code", "execution_count": 74, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "a\n", "b\n", "c\n" ] } ], "source": [ "s = 'abc'\n", "for element in s:\n", " print(element)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "``range()`` objects are iterable" ] }, { "cell_type": "code", "execution_count": 75, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0\n", "1\n", "2\n" ] } ], "source": [ "r = range(3)\n", "for element in r:\n", " print(element)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "``dict`` is iterable" ] }, { "cell_type": "code", "execution_count": 76, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1\n", "2\n" ] } ], "source": [ "d = {1:'one', 2: 'two'}\n", "for element in d:\n", " print(element)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## ``list()``, and iterable?" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "What does the ``list`` constructor do with its parameter if you pass it one?" ] }, { "cell_type": "code", "execution_count": 77, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[]" ] }, "execution_count": 77, "metadata": {}, "output_type": "execute_result" } ], "source": [ "l = list()\n", "l" ] }, { "cell_type": "code", "execution_count": 78, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[0, 1, 2]" ] }, "execution_count": 78, "metadata": {}, "output_type": "execute_result" } ], "source": [ "r = range(3)\n", "list(r)" ] }, { "cell_type": "code", "execution_count": 79, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['a', 'b', 'c']" ] }, "execution_count": 79, "metadata": {}, "output_type": "execute_result" } ], "source": [ "list('abc')" ] }, { "cell_type": "code", "execution_count": 80, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1\n", "2\n", "3\n" ] } ], "source": [ "l = [1,2,3]\n", "for element in l:\n", " print(element)" ] }, { "cell_type": "code", "execution_count": 81, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 2, 3]" ] }, "execution_count": 81, "metadata": {}, "output_type": "execute_result" } ], "source": [ "list(l)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Tuple Unpacking and the Rest" ] }, { "cell_type": "code", "execution_count": 82, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1 2 [3, 4, 5, 6]\n" ] } ], "source": [ "l = [1, 2, 3, 4, 5, 6]\n", "a, b, *rest = l\n", "print(a, b, rest)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Decorators, etc." ] }, { "cell_type": "code", "execution_count": 83, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "function add has name add, and is documented like so: das ist der docstring der extrem komplexen funktion add()\n", "add called: args=(1, 2), kwargs={}\n", "add (args) 3\n", "add called: args=(), kwargs={'a': 1, 'b': 2}\n", "add (kwargs) 3\n", "square called: args=(10,), kwargs={}\n", "square 100\n" ] } ], "source": [ "import functools\n", "\n", "def debug(func):\n", " @functools.wraps(func)\n", " def wrapper(*args, **kwargs):\n", " print(f'{func.__name__} called: args={args}, kwargs={kwargs}')\n", " return func(*args, **kwargs)\n", " return wrapper\n", "\n", "# add = debug(add)\n", "@debug\n", "def add(a, b):\n", " 'das ist der docstring der extrem komplexen funktion add()'\n", " return a+b\n", "\n", "@debug\n", "def square(a):\n", " return a**2\n", "\n", "print(f'function add has name {add.__name__}, and is documented like so: {add.__doc__}')\n", "print('add (args)', add(1, 2))\n", "print('add (kwargs)', add(a=1, b=2))\n", "print('square', square(10))\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# ``NoneType`` and ``None``" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Remember ``NULL`` in C?" ] }, { "cell_type": "code", "execution_count": 84, "metadata": {}, "outputs": [], "source": [ "a = None" ] }, { "cell_type": "code", "execution_count": 85, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "NoneType" ] }, "execution_count": 85, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(a)" ] }, { "cell_type": "code", "execution_count": 86, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'one'" ] }, "execution_count": 86, "metadata": {}, "output_type": "execute_result" } ], "source": [ "d = { 1:'one', 2:'two' }\n", "d[1]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Index Operator crashes if key not there ..." ] }, { "cell_type": "code", "execution_count": 87, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " 3\n" ] } ], "source": [ "try:\n", " d[3]\n", "except KeyError as e:\n", " print(type(e), e)" ] }, { "cell_type": "code", "execution_count": 88, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "None\n" ] } ], "source": [ "value = d.get(3)\n", "print(value)" ] }, { "cell_type": "code", "execution_count": 89, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "not there\n" ] } ], "source": [ "value = d.get(3)\n", "if value is None:\n", " print('not there')\n", "else:\n", " print(value)" ] }, { "cell_type": "code", "execution_count": 90, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "None\n" ] } ], "source": [ "def f():\n", " pass # does nothing, not even return anything\n", "result = f()\n", "print(result)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# File I/O" ] }, { "cell_type": "code", "execution_count": 91, "metadata": {}, "outputs": [], "source": [ "f = open('testfile.txt')" ] }, { "cell_type": "code", "execution_count": 92, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'zeile 1\\nzeile 2\\nzeile 3\\n'" ] }, "execution_count": 92, "metadata": {}, "output_type": "execute_result" } ], "source": [ "f.read()" ] }, { "cell_type": "code", "execution_count": 93, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0" ] }, "execution_count": 93, "metadata": {}, "output_type": "execute_result" } ], "source": [ "f.seek(0)" ] }, { "cell_type": "code", "execution_count": 94, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'zeile 1\\n'" ] }, "execution_count": 94, "metadata": {}, "output_type": "execute_result" } ], "source": [ "f.readline()" ] }, { "cell_type": "code", "execution_count": 95, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'zeile 2\\n'" ] }, "execution_count": 95, "metadata": {}, "output_type": "execute_result" } ], "source": [ "f.readline()" ] }, { "cell_type": "code", "execution_count": 96, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'zeile 3\\n'" ] }, "execution_count": 96, "metadata": {}, "output_type": "execute_result" } ], "source": [ "f.readline()" ] }, { "cell_type": "code", "execution_count": 97, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "''" ] }, "execution_count": 97, "metadata": {}, "output_type": "execute_result" } ], "source": [ "f.readline() # EOF" ] }, { "cell_type": "code", "execution_count": 98, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0" ] }, "execution_count": 98, "metadata": {}, "output_type": "execute_result" } ], "source": [ "f.seek(0)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Files are *iterable*" ] }, { "cell_type": "code", "execution_count": 99, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "zeile 1\n", "\n", "zeile 2\n", "\n", "zeile 3\n", "\n" ] } ], "source": [ "for line in f:\n", " print(line)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Iteration, ``yield``, Recursion" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Recursion" ] }, { "cell_type": "code", "execution_count": 106, "metadata": {}, "outputs": [], "source": [ "def nth_fibo(n):\n", " if n < 1:\n", " raise RuntimeError('No fibonacci number below 1')\n", " if n == 1 or n == 2:\n", " return 1\n", " return nth_fibo(n-1) + nth_fibo(n-2)" ] }, { "cell_type": "code", "execution_count": 107, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "13" ] }, "execution_count": 107, "metadata": {}, "output_type": "execute_result" } ], "source": [ "nth_fibo(7)" ] }, { "cell_type": "code", "execution_count": 108, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 108, "metadata": {}, "output_type": "execute_result" } ], "source": [ "nth_fibo(2)" ] }, { "cell_type": "code", "execution_count": 113, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "No fibonacci number below 1\n" ] } ], "source": [ "try:\n", " nth_fibo(0)\n", "except RuntimeError as e:\n", " print(e)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Iteratively Calculating Fibonacci Numbers -> ``yield``" ] }, { "cell_type": "code", "execution_count": 119, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1\n", "1\n", "2\n", "3\n", "5\n", "8\n", "13\n", "21\n", "34\n", "55\n" ] } ], "source": [ "N = 10 - 2 # 2 to accomodate first and second\n", "\n", "first, second = 1, 1\n", "print(first)\n", "print(second)\n", "while N > 0:\n", " N -= 1\n", " third = first + second\n", " print(third)\n", " first, second = second, third" ] }, { "cell_type": "code", "execution_count": 121, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1\n", "1\n", "2\n", "3\n", "5\n", "8\n", "13\n", "21\n", "34\n", "55\n" ] } ], "source": [ "first, second = 1, 1\n", "print(first)\n", "print(second)\n", "for i in range(8):\n", " third = first + second\n", " print(third)\n", " first, second = second, third" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Function to calculate a list of first N fibonacci numbers ..." ] }, { "cell_type": "code", "execution_count": 122, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1\n", "1\n", "2\n", "3\n", "5\n", "8\n", "13\n", "21\n", "34\n", "55\n" ] } ], "source": [ "def fibo(n):\n", " 'Returns a list of first n fibonacci numbers'\n", " nums = []\n", " first, second = 1, 1\n", " nums.append(first)\n", " nums.append(second)\n", " for i in range(n-2):\n", " third = first + second\n", " nums.append(third)\n", " first, second = second, third\n", " return nums\n", "\n", "# user can do what she wants with those numbers. for example, print them\n", "for n in fibo(10):\n", " print(n)" ] }, { "cell_type": "code", "execution_count": 123, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1\n", "1\n", "2\n", "3\n", "5\n", "8\n", "13\n", "21\n", "34\n", "55\n" ] } ], "source": [ "def fibo(n):\n", " 'Returns an iterable that generates the first n fibonacci numbers'\n", " first, second = 1, 1\n", " yield first\n", " yield second\n", " for i in range(n-2):\n", " third = first + second\n", " yield third\n", " first, second = second, third\n", "\n", "# user can do what she wants with those numbers. for example, print them\n", "for n in fibo(10):\n", " print(n)" ] }, { "cell_type": "code", "execution_count": 124, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "" ] }, "execution_count": 124, "metadata": {}, "output_type": "execute_result" } ], "source": [ "f = fibo(4)\n", "f" ] }, { "cell_type": "code", "execution_count": 125, "metadata": {}, "outputs": [], "source": [ "it = iter(f)" ] }, { "cell_type": "code", "execution_count": 126, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 126, "metadata": {}, "output_type": "execute_result" } ], "source": [ "next(it)" ] }, { "cell_type": "code", "execution_count": 127, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 127, "metadata": {}, "output_type": "execute_result" } ], "source": [ "next(it)" ] }, { "cell_type": "code", "execution_count": 128, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "2" ] }, "execution_count": 128, "metadata": {}, "output_type": "execute_result" } ], "source": [ "next(it)" ] }, { "cell_type": "code", "execution_count": 129, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "3" ] }, "execution_count": 129, "metadata": {}, "output_type": "execute_result" } ], "source": [ "next(it)" ] }, { "cell_type": "code", "execution_count": 131, "metadata": {}, "outputs": [], "source": [ "try:\n", " next(it)\n", "except StopIteration:\n", " pass" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## ``map()``, ``filter()``, ``zip()``, ``enumerate()`` ..." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## ``map()``, and several other ways to do the same" ] }, { "cell_type": "code", "execution_count": 132, "metadata": {}, "outputs": [], "source": [ "l = ['1.2', '3.4', '666.0']" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Use a list comprehension to transform ``l`` to floats" ] }, { "cell_type": "code", "execution_count": 134, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1.2, 3.4, 666.0]" ] }, "execution_count": 134, "metadata": {}, "output_type": "execute_result" } ], "source": [ "lf = [float(element) for element in l]\n", "lf" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Use ``map()`` to do the same" ] }, { "cell_type": "code", "execution_count": 135, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "" ] }, "execution_count": 135, "metadata": {}, "output_type": "execute_result" } ], "source": [ "lf = map(float, l)\n", "lf" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Ah, have to iterate over the iterable to see the generated items" ] }, { "cell_type": "code", "execution_count": 136, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1.2\n", "3.4\n", "666.0\n" ] } ], "source": [ "for e in lf:\n", " print(e)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Use a generator expression to do the same" ] }, { "cell_type": "code", "execution_count": 138, "metadata": {}, "outputs": [ { "data": { "text/plain": [ " at 0x7fd9801b4900>" ] }, "execution_count": 138, "metadata": {}, "output_type": "execute_result" } ], "source": [ "lf = (float(e) for e in l)\n", "lf" ] }, { "cell_type": "code", "execution_count": 139, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1.2\n", "3.4\n", "666.0\n" ] } ], "source": [ "for e in lf:\n", " print(e)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### ``zip()``" ] }, { "cell_type": "code", "execution_count": 140, "metadata": {}, "outputs": [], "source": [ "l1 = [1, 2, 3, 4]\n", "l2 = ['one', 'two', 'three', 'four']" ] }, { "cell_type": "code", "execution_count": 142, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "" ] }, "execution_count": 142, "metadata": {}, "output_type": "execute_result" } ], "source": [ "zipped = zip(l1, l2)\n", "zipped" ] }, { "cell_type": "code", "execution_count": 143, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "(1, 'one')\n", "(2, 'two')\n", "(3, 'three')\n", "(4, 'four')\n" ] } ], "source": [ "for element in zipped:\n", " print(element)" ] }, { "cell_type": "code", "execution_count": 144, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{1: 'one', 2: 'two', 3: 'three', 4: 'four'}" ] }, "execution_count": 144, "metadata": {}, "output_type": "execute_result" } ], "source": [ "dict(zip(l1, l2))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "What if both are not of equal lengths?" ] }, { "cell_type": "code", "execution_count": 145, "metadata": {}, "outputs": [], "source": [ "l1 = [1, 2, 3, 4, 5]\n", "l2 = ['one', 'two', 'three', 'four']" ] }, { "cell_type": "code", "execution_count": 146, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1 one\n", "2 two\n", "3 three\n", "4 four\n" ] } ], "source": [ "for l, r in zip(l1, l2):\n", " print(l, r)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### ``filter()``, and several other methods to do the same" ] }, { "cell_type": "code", "execution_count": 147, "metadata": {}, "outputs": [], "source": [ "numbers = range(10)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We want even numbers only:" ] }, { "cell_type": "code", "execution_count": 148, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0\n", "2\n", "4\n", "6\n", "8\n" ] } ], "source": [ "def even(n):\n", " return n%2 == 0\n", "for e in filter(even, numbers):\n", " print(e)" ] }, { "cell_type": "code", "execution_count": 150, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0\n", "2\n", "4\n", "6\n", "8\n" ] } ], "source": [ "for e in filter(lambda n: n%2 == 0, range(10)):\n", " print(e)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Use a list comprehension to do the same" ] }, { "cell_type": "code", "execution_count": 158, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[0, 2, 4, 6, 8]" ] }, "execution_count": 158, "metadata": {}, "output_type": "execute_result" } ], "source": [ "[element for element in range(10) if element%2 == 0]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Use a generator expression to achieve ultimate beauty and performance" ] }, { "cell_type": "code", "execution_count": 160, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0\n", "2\n", "4\n", "6\n", "8\n" ] } ], "source": [ "gen = (element for element in range(10) if element%2 == 0)\n", "for e in gen:\n", " print(e)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### ``enumerate()``" ] }, { "cell_type": "code", "execution_count": 151, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "(0, 'one')\n", "(1, 'two')\n", "(2, 'three')\n", "(3, 'four')\n" ] } ], "source": [ "l = ['one', 'two', 'three', 'four']\n", "for element in enumerate(l):\n", " print(element)" ] }, { "cell_type": "code", "execution_count": 152, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0 one\n", "1 two\n", "2 three\n", "3 four\n" ] } ], "source": [ "l = ['one', 'two', 'three', 'four']\n", "for sequenceno, s in enumerate(l):\n", " print(sequenceno, s)" ] }, { "cell_type": "code", "execution_count": 153, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1 one\n", "2 two\n", "3 three\n", "4 four\n" ] } ], "source": [ "l = ['one', 'two', 'three', 'four']\n", "for sequenceno, s in enumerate(l, 1):\n", " print(sequenceno, s)" ] }, { "cell_type": "code", "execution_count": 154, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "(1, 'one')\n", "(2, 'two')\n", "(3, 'three')\n", "(4, 'four')\n" ] } ], "source": [ "l = ['one', 'two', 'three', 'four']\n", "for kv_pair in enumerate(l, 1):\n", " print(kv_pair)" ] }, { "cell_type": "code", "execution_count": 155, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{1: 'one', 2: 'two', 3: 'three', 4: 'four'}" ] }, "execution_count": 155, "metadata": {}, "output_type": "execute_result" } ], "source": [ "dict(enumerate(l, 1))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# ``OSError``, ``errno``" ] }, { "cell_type": "code", "execution_count": 164, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[Errno 13] Permission denied: '/etc/passwd'\n", "errno is, btw, 13\n" ] } ], "source": [ "import os\n", "try:\n", " os.remove('/etc/passwd')\n", "except PermissionError as e:\n", " print(e)\n", " print(f'errno is, btw, {e.errno}')" ] }, { "cell_type": "code", "execution_count": 168, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "13" ] }, "execution_count": 168, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import errno\n", "errno.EACCES" ] }, { "cell_type": "code", "execution_count": 169, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 169, "metadata": {}, "output_type": "execute_result" } ], "source": [ "issubclass(PermissionError, OSError)" ] }, { "cell_type": "code", "execution_count": 170, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 170, "metadata": {}, "output_type": "execute_result" } ], "source": [ "issubclass(FileNotFoundError, OSError)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# The ``platform`` Module, ``sys.path``" ] }, { "cell_type": "code", "execution_count": 171, "metadata": {}, "outputs": [], "source": [ "import platform" ] }, { "cell_type": "code", "execution_count": 175, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "('64bit', 'ELF')" ] }, "execution_count": 175, "metadata": {}, "output_type": "execute_result" } ], "source": [ "platform.architecture()" ] }, { "cell_type": "code", "execution_count": 178, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'x86_64'" ] }, "execution_count": 178, "metadata": {}, "output_type": "execute_result" } ], "source": [ "platform.machine()" ] }, { "cell_type": "code", "execution_count": 183, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'x86_64'" ] }, "execution_count": 183, "metadata": {}, "output_type": "execute_result" } ], "source": [ "platform.processor()" ] }, { "cell_type": "code", "execution_count": 186, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'#1 SMP Wed Apr 21 13:18:33 UTC 2021'" ] }, "execution_count": 186, "metadata": {}, "output_type": "execute_result" } ], "source": [ "platform.version()" ] }, { "cell_type": "code", "execution_count": 188, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'CPython'" ] }, "execution_count": 188, "metadata": {}, "output_type": "execute_result" } ], "source": [ "platform.python_implementation()" ] }, { "cell_type": "code", "execution_count": 190, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "('3', '9', '4')" ] }, "execution_count": 190, "metadata": {}, "output_type": "execute_result" } ], "source": [ "platform.python_version_tuple()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Module search path**" ] }, { "cell_type": "code", "execution_count": 191, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['/home/jfasch/work/jfasch-home/trainings/log/detail/2021-05-25',\n", " '/home/jfasch/work/openheating',\n", " '/home/jfasch/work/jfasch-home',\n", " '/home/jfasch/work/jfasch-home/trainings/log/detail/2021-05-25',\n", " '/usr/lib64/python39.zip',\n", " '/usr/lib64/python3.9',\n", " '/usr/lib64/python3.9/lib-dynload',\n", " '',\n", " '/home/jfasch/venv/homepage/lib64/python3.9/site-packages',\n", " '/home/jfasch/venv/homepage/lib/python3.9/site-packages',\n", " '/home/jfasch/venv/homepage/lib64/python3.9/site-packages/IPython/extensions',\n", " '/home/jfasch/.ipython']" ] }, "execution_count": 191, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import sys\n", "sys.path" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# ``os.path``" ] }, { "cell_type": "code", "execution_count": 193, "metadata": {}, "outputs": [], "source": [ "import os.path" ] }, { "cell_type": "code", "execution_count": 194, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 194, "metadata": {}, "output_type": "execute_result" } ], "source": [ "os.path.exists('/etc/passwd')" ] }, { "cell_type": "code", "execution_count": 196, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 196, "metadata": {}, "output_type": "execute_result" } ], "source": [ "os.path.isfile('/etc/passwd')" ] }, { "cell_type": "code", "execution_count": 197, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 197, "metadata": {}, "output_type": "execute_result" } ], "source": [ "os.path.isdir('/etc/passwd')" ] }, { "cell_type": "code", "execution_count": 198, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'/'" ] }, "execution_count": 198, "metadata": {}, "output_type": "execute_result" } ], "source": [ "os.sep" ] }, { "cell_type": "code", "execution_count": 200, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'../lib'" ] }, "execution_count": 200, "metadata": {}, "output_type": "execute_result" } ], "source": [ "my_path = '..' + os.sep + 'lib'\n", "my_path" ] }, { "cell_type": "code", "execution_count": 201, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'../lib'" ] }, "execution_count": 201, "metadata": {}, "output_type": "execute_result" } ], "source": [ "my_path = os.path.join('..', 'lib')\n", "my_path" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Exceptions und so (``assert()``)" ] }, { "cell_type": "code", "execution_count": 202, "metadata": {}, "outputs": [], "source": [ "try:\n", " open('some-file-that-hopefully-does-not-exist')\n", "except FileNotFoundError as e:\n", " the_exception = e" ] }, { "cell_type": "code", "execution_count": 203, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "FileNotFoundError(2, 'No such file or directory')" ] }, "execution_count": 203, "metadata": {}, "output_type": "execute_result" } ], "source": [ "the_exception" ] }, { "cell_type": "code", "execution_count": 204, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 204, "metadata": {}, "output_type": "execute_result" } ], "source": [ "isinstance(the_exception, FileNotFoundError)" ] }, { "cell_type": "code", "execution_count": 205, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "FileNotFoundError" ] }, "execution_count": 205, "metadata": {}, "output_type": "execute_result" } ], "source": [ "the_exception.__class__" ] }, { "cell_type": "code", "execution_count": 207, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(OSError,)" ] }, "execution_count": 207, "metadata": {}, "output_type": "execute_result" } ], "source": [ "the_exception.__class__.__bases__" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Ah , ``OSError``" ] }, { "cell_type": "code", "execution_count": 209, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(Exception,)" ] }, "execution_count": 209, "metadata": {}, "output_type": "execute_result" } ], "source": [ "OSError.__bases__" ] }, { "cell_type": "code", "execution_count": 210, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(BaseException,)" ] }, "execution_count": 210, "metadata": {}, "output_type": "execute_result" } ], "source": [ "Exception.__bases__" ] }, { "cell_type": "code", "execution_count": 211, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(object,)" ] }, "execution_count": 211, "metadata": {}, "output_type": "execute_result" } ], "source": [ "BaseException.__bases__" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "And ``StopIteration``? Where is that in the hierarchy?" ] }, { "cell_type": "code", "execution_count": 221, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(Exception,)" ] }, "execution_count": 221, "metadata": {}, "output_type": "execute_result" } ], "source": [ "StopIteration.__bases__" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## AssertionError" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\"To assert\" stands for \"make sure that a condition holds\"" ] }, { "cell_type": "code", "execution_count": 212, "metadata": {}, "outputs": [], "source": [ "l = []\n", "l.append(1)\n", "l.append(2)\n", "l.append(3)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here the list must have three elements, we know that for sure." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Distrusting the ``list`` class (Guido is incompetent)" ] }, { "cell_type": "code", "execution_count": 216, "metadata": {}, "outputs": [], "source": [ "assert len(l) == 3 # well, that precondition holds" ] }, { "cell_type": "code", "execution_count": 219, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Shit happened: \n" ] } ], "source": [ "# being too stupid for distrust altogether (I appended three items, not four)\n", "try:\n", " assert len(l) == 4\n", "except AssertionError as e:\n", " print('Shit happened:', type(e))" ] }, { "cell_type": "code", "execution_count": 220, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(Exception,)" ] }, "execution_count": 220, "metadata": {}, "output_type": "execute_result" } ], "source": [ "AssertionError.__bases__" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Random Questions" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1\n", "2\n" ] } ], "source": [ "for i in range(1,3):\n", " print(i)" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[0, 0]" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "my_list = [0 for i in range(1,3)]\n", "my_list" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Slicing" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'beg'" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s = 'abdefg'\n", "s[1::2]" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'bdefg'" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s[1:]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## OO" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note: ``self`` is *the object*" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2 5\n" ] } ], "source": [ "class Point:\n", " def __init__(self, x, y):\n", " self.x = x\n", " self.y = y\n", "\n", "p = Point(2, 5)\n", "print(p.x, p.y)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "How to stringify an object?" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "42\n" ] } ], "source": [ "i = 42\n", "print(i)" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'42'" ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "str(i)" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'42'" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "i.__str__()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "And ``class Point``?" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "<__main__.Point object at 0x7ffa9c2ac3a0>\n" ] } ], "source": [ "p = Point(1, 2)\n", "print(p)" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "(2, 5)\n" ] } ], "source": [ "class Point:\n", " def __init__(self, x, y):\n", " self.x = x\n", " self.y = y\n", " def __str__(self):\n", " return f'({self.x}, {self.y})'\n", "\n", "p = Point(2, 5)\n", "print(p)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## String Formatting" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [], "source": [ "formatstring = 'das ist ein ding: {}, und noch eins: {}'" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'das ist ein ding: 666, und noch eins: eugenie'" ] }, "execution_count": 25, "metadata": {}, "output_type": "execute_result" } ], "source": [ "formatierter_string = formatstring.format(666, 'eugenie')\n", "formatierter_string" ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'das ist ein ding: eugenie, und noch eins: 666'" ] }, "execution_count": 28, "metadata": {}, "output_type": "execute_result" } ], "source": [ "formatstring = 'das ist ein ding: {a}, und noch eins: {b}'\n", "formatstring.format(b=666, a='eugenie')" ] }, { "cell_type": "code", "execution_count": 31, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'das ist {a} und eugenie ist auch noch dabei'" ] }, "execution_count": 31, "metadata": {}, "output_type": "execute_result" } ], "source": [ "'das ist {a} ' + 'und {b} ist auch noch dabei'.format(a=666, b='eugenie')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## ``import datetime``" ] }, { "cell_type": "code", "execution_count": 44, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'1'" ] }, "execution_count": 44, "metadata": {}, "output_type": "execute_result" } ], "source": [ "'{a}'.format(a=1)" ] }, { "cell_type": "code", "execution_count": 46, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "' 1'" ] }, "execution_count": 46, "metadata": {}, "output_type": "execute_result" } ], "source": [ "'{a:5}'.format(a=1)" ] }, { "cell_type": "code", "execution_count": 48, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'1 '" ] }, "execution_count": 48, "metadata": {}, "output_type": "execute_result" } ], "source": [ "'{a:<5}'.format(a=1)" ] }, { "cell_type": "code", "execution_count": 49, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "' 1'" ] }, "execution_count": 49, "metadata": {}, "output_type": "execute_result" } ], "source": [ "'{a:>5}'.format(a=1)" ] }, { "cell_type": "code", "execution_count": 50, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'01'" ] }, "execution_count": 50, "metadata": {}, "output_type": "execute_result" } ], "source": [ "'{a:02}'.format(a=1)" ] } ], "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.9.4" } }, "nbformat": 4, "nbformat_minor": 4 }