{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Wiederholung" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [], "source": [ "v = 666" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "int" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(v)" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [], "source": [ "v = 1.234" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "float" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(v)" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [], "source": [ "v = [1, 2.5, 'drei', {1: 'eins', 2: 'zwei'}]" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "list" ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(v)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Mutable/Immutable" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [], "source": [ "l = [1,2,'drei']" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [], "source": [ "l.append('vier')" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 2, 'drei', 'vier']" ] }, "execution_count": 17, "metadata": {}, "output_type": "execute_result" } ], "source": [ "l" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [], "source": [ "t = (1,2,'drei')" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "tuple" ] }, "execution_count": 20, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(t)" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " 'tuple' object has no attribute 'append'\n" ] } ], "source": [ "try:\n", " t.append('vier')\n", "except Exception as e:\n", " print(type(e), e)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Attribute" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [], "source": [ "l.append(5.0)" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [], "source": [ "import sys" ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "module" ] }, "execution_count": 26, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(sys)" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'linux'" ] }, "execution_count": 27, "metadata": {}, "output_type": "execute_result" } ], "source": [ "sys.platform" ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['/home/jfasch/venv/jfasch-home/lib64/python3.9/site-packages/ipykernel_launcher.py',\n", " '-f',\n", " '/home/jfasch/.local/share/jupyter/runtime/kernel-51139385-5832-4866-9768-77397a312b47.json']" ] }, "execution_count": 28, "metadata": {}, "output_type": "execute_result" } ], "source": [ "sys.argv" ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on built-in module sys:\n", "\n", "NAME\n", " sys\n", "\n", "MODULE REFERENCE\n", " https://docs.python.org/3.9/library/sys\n", " \n", " The following documentation is automatically generated from the Python\n", " source files. It may be incomplete, incorrect or include features that\n", " are considered implementation detail and may vary between Python\n", " implementations. When in doubt, consult the module reference at the\n", " location listed above.\n", "\n", "DESCRIPTION\n", " This module provides access to some objects used or maintained by the\n", " interpreter and to functions that interact strongly with the interpreter.\n", " \n", " Dynamic objects:\n", " \n", " argv -- command line arguments; argv[0] is the script pathname if known\n", " path -- module search path; path[0] is the script directory, else ''\n", " modules -- dictionary of loaded modules\n", " \n", " displayhook -- called to show results in an interactive session\n", " excepthook -- called to handle any uncaught exception other than SystemExit\n", " To customize printing in an interactive session or to install a custom\n", " top-level exception handler, assign other functions to replace these.\n", " \n", " stdin -- standard input file object; used by input()\n", " stdout -- standard output file object; used by print()\n", " stderr -- standard error object; used for error messages\n", " By assigning other file objects (or objects that behave like files)\n", " to these, it is possible to redirect all of the interpreter's I/O.\n", " \n", " last_type -- type of last uncaught exception\n", " last_value -- value of last uncaught exception\n", " last_traceback -- traceback of last uncaught exception\n", " These three are only available in an interactive session after a\n", " traceback has been printed.\n", " \n", " Static objects:\n", " \n", " builtin_module_names -- tuple of module names built into this interpreter\n", " copyright -- copyright notice pertaining to this interpreter\n", " exec_prefix -- prefix used to find the machine-specific Python library\n", " executable -- absolute path of the executable binary of the Python interpreter\n", " float_info -- a named tuple with information about the float implementation.\n", " float_repr_style -- string indicating the style of repr() output for floats\n", " hash_info -- a named tuple with information about the hash algorithm.\n", " hexversion -- version information encoded as a single integer\n", " implementation -- Python implementation information.\n", " int_info -- a named tuple with information about the int implementation.\n", " maxsize -- the largest supported length of containers.\n", " maxunicode -- the value of the largest Unicode code point\n", " platform -- platform identifier\n", " prefix -- prefix used to find the Python library\n", " thread_info -- a named tuple with information about the thread implementation.\n", " version -- the version of this interpreter as a string\n", " version_info -- version information as a named tuple\n", " __stdin__ -- the original stdin; don't touch!\n", " __stdout__ -- the original stdout; don't touch!\n", " __stderr__ -- the original stderr; don't touch!\n", " __displayhook__ -- the original displayhook; don't touch!\n", " __excepthook__ -- the original excepthook; don't touch!\n", " \n", " Functions:\n", " \n", " displayhook() -- print an object to the screen, and save it in builtins._\n", " excepthook() -- print an exception and its traceback to sys.stderr\n", " exc_info() -- return thread-safe information about the current exception\n", " exit() -- exit the interpreter by raising SystemExit\n", " getdlopenflags() -- returns flags to be used for dlopen() calls\n", " getprofile() -- get the global profiling function\n", " getrefcount() -- return the reference count for an object (plus one :-)\n", " getrecursionlimit() -- return the max recursion depth for the interpreter\n", " getsizeof() -- return the size of an object in bytes\n", " gettrace() -- get the global debug tracing function\n", " setdlopenflags() -- set the flags to be used for dlopen() calls\n", " setprofile() -- set the global profiling function\n", " setrecursionlimit() -- set the max recursion depth for the interpreter\n", " settrace() -- set the global debug tracing function\n", "\n", "FUNCTIONS\n", " __breakpointhook__ = breakpointhook(...)\n", " breakpointhook(*args, **kws)\n", " \n", " This hook function is called by built-in breakpoint().\n", " \n", " __displayhook__ = displayhook(object, /)\n", " Print an object to sys.stdout and also save it in builtins._\n", " \n", " __excepthook__ = excepthook(exctype, value, traceback, /)\n", " Handle an exception by displaying it with a traceback on sys.stderr.\n", " \n", " __unraisablehook__ = unraisablehook(unraisable, /)\n", " Handle an unraisable exception.\n", " \n", " The unraisable argument has the following attributes:\n", " \n", " * exc_type: Exception type.\n", " * exc_value: Exception value, can be None.\n", " * exc_traceback: Exception traceback, can be None.\n", " * err_msg: Error message, can be None.\n", " * object: Object causing the exception, can be None.\n", " \n", " addaudithook(hook)\n", " Adds a new audit hook callback.\n", " \n", " audit(...)\n", " audit(event, *args)\n", " \n", " Passes the event to any audit hooks that are attached.\n", " \n", " call_tracing(func, args, /)\n", " Call func(*args), while tracing is enabled.\n", " \n", " The tracing state is saved, and restored afterwards. This is intended\n", " to be called from a debugger from a checkpoint, to recursively debug\n", " some other code.\n", " \n", " exc_info()\n", " Return current exception information: (type, value, traceback).\n", " \n", " Return information about the most recent exception caught by an except\n", " clause in the current stack frame or in an older stack frame.\n", " \n", " exit(status=None, /)\n", " Exit the interpreter by raising SystemExit(status).\n", " \n", " If the status is omitted or None, it defaults to zero (i.e., success).\n", " If the status is an integer, it will be used as the system exit status.\n", " If it is another kind of object, it will be printed and the system\n", " exit status will be one (i.e., failure).\n", " \n", " get_asyncgen_hooks()\n", " Return the installed asynchronous generators hooks.\n", " \n", " This returns a namedtuple of the form (firstiter, finalizer).\n", " \n", " get_coroutine_origin_tracking_depth()\n", " Check status of origin tracking for coroutine objects in this thread.\n", " \n", " getallocatedblocks()\n", " Return the number of memory blocks currently allocated.\n", " \n", " getdefaultencoding()\n", " Return the current default encoding used by the Unicode implementation.\n", " \n", " getdlopenflags()\n", " Return the current value of the flags that are used for dlopen calls.\n", " \n", " The flag constants are defined in the os module.\n", " \n", " getfilesystemencodeerrors()\n", " Return the error mode used Unicode to OS filename conversion.\n", " \n", " getfilesystemencoding()\n", " Return the encoding used to convert Unicode filenames to OS filenames.\n", " \n", " getprofile()\n", " Return the profiling function set with sys.setprofile.\n", " \n", " See the profiler chapter in the library manual.\n", " \n", " getrecursionlimit()\n", " Return the current value of the recursion limit.\n", " \n", " The recursion limit is the maximum depth of the Python interpreter\n", " stack. This limit prevents infinite recursion from causing an overflow\n", " of the C stack and crashing Python.\n", " \n", " getrefcount(object, /)\n", " Return the reference count of object.\n", " \n", " The count returned is generally one higher than you might expect,\n", " because it includes the (temporary) reference as an argument to\n", " getrefcount().\n", " \n", " getsizeof(...)\n", " getsizeof(object [, default]) -> int\n", " \n", " Return the size of object in bytes.\n", " \n", " getswitchinterval()\n", " Return the current thread switch interval; see sys.setswitchinterval().\n", " \n", " gettrace()\n", " Return the global debug tracing function set with sys.settrace.\n", " \n", " See the debugger chapter in the library manual.\n", " \n", " intern(string, /)\n", " ``Intern'' the given string.\n", " \n", " This enters the string in the (global) table of interned strings whose\n", " purpose is to speed up dictionary lookups. Return the string itself or\n", " the previously interned string object with the same value.\n", " \n", " is_finalizing()\n", " Return True if Python is exiting.\n", " \n", " set_asyncgen_hooks(...)\n", " set_asyncgen_hooks(* [, firstiter] [, finalizer])\n", " \n", " Set a finalizer for async generators objects.\n", " \n", " set_coroutine_origin_tracking_depth(depth)\n", " Enable or disable origin tracking for coroutine objects in this thread.\n", " \n", " Coroutine objects will track 'depth' frames of traceback information\n", " about where they came from, available in their cr_origin attribute.\n", " \n", " Set a depth of 0 to disable.\n", " \n", " setdlopenflags(flags, /)\n", " Set the flags used by the interpreter for dlopen calls.\n", " \n", " This is used, for example, when the interpreter loads extension\n", " modules. Among other things, this will enable a lazy resolving of\n", " symbols when importing a module, if called as sys.setdlopenflags(0).\n", " To share symbols across extension modules, call as\n", " sys.setdlopenflags(os.RTLD_GLOBAL). Symbolic names for the flag\n", " modules can be found in the os module (RTLD_xxx constants, e.g.\n", " os.RTLD_LAZY).\n", " \n", " setprofile(...)\n", " setprofile(function)\n", " \n", " Set the profiling function. It will be called on each function call\n", " and return. See the profiler chapter in the library manual.\n", " \n", " setrecursionlimit(limit, /)\n", " Set the maximum depth of the Python interpreter stack to n.\n", " \n", " This limit prevents infinite recursion from causing an overflow of the C\n", " stack and crashing Python. The highest possible limit is platform-\n", " dependent.\n", " \n", " setswitchinterval(interval, /)\n", " Set the ideal thread switching delay inside the Python interpreter.\n", " \n", " The actual frequency of switching threads can be lower if the\n", " interpreter executes long sequences of uninterruptible code\n", " (this is implementation-specific and workload-dependent).\n", " \n", " The parameter must represent the desired switching delay in seconds\n", " A typical value is 0.005 (5 milliseconds).\n", " \n", " settrace(...)\n", " settrace(function)\n", " \n", " Set the global debug tracing function. It will be called on each\n", " function call. See the debugger chapter in the library manual.\n", " \n", " unraisablehook(unraisable, /)\n", " Handle an unraisable exception.\n", " \n", " The unraisable argument has the following attributes:\n", " \n", " * exc_type: Exception type.\n", " * exc_value: Exception value, can be None.\n", " * exc_traceback: Exception traceback, can be None.\n", " * err_msg: Error message, can be None.\n", " * object: Object causing the exception, can be None.\n", "\n", "DATA\n", " __stderr__ = <_io.TextIOWrapper name='' mode='w' encoding='utf...\n", " __stdin__ = <_io.TextIOWrapper name='' mode='r' encoding='utf-8...\n", " __stdout__ = <_io.TextIOWrapper name='' mode='w' encoding='utf...\n", " abiflags = ''\n", " api_version = 1013\n", " argv = ['/home/jfasch/venv/jfasch-home/lib64/python3.9/site-packages/i...\n", " base_exec_prefix = '/usr'\n", " base_prefix = '/usr'\n", " builtin_module_names = ('_abc', '_ast', '_codecs', '_collections', '_f...\n", " byteorder = 'little'\n", " copyright = 'Copyright (c) 2001-2022 Python Software Foundati...ematis...\n", " displayhook = \n", " dont_write_bytecode = False\n", " exec_prefix = '/home/jfasch/venv/jfasch-home'\n", " executable = '/home/jfasch/venv/jfasch-home/bin/python'\n", " flags = sys.flags(debug=0, inspect=0, interactive=0, opt...ation=1, is...\n", " float_info = sys.float_info(max=1.7976931348623157e+308, max_...epsilo...\n", " float_repr_style = 'short'\n", " hash_info = sys.hash_info(width=64, modulus=2305843009213693...iphash2...\n", " hexversion = 50924272\n", " implementation = namespace(name='cpython', cache_tag='cpython-39'...xv...\n", " int_info = sys.int_info(bits_per_digit=30, sizeof_digit=4)\n", " last_value = AttributeError(\"'tuple' object has no attribute 'append'\"...\n", " maxsize = 9223372036854775807\n", " maxunicode = 1114111\n", " meta_path = [, , \n", " stdin = <_io.TextIOWrapper name='' mode='r' encoding='utf-8'>\n", " stdout = \n", " thread_info = sys.thread_info(name='pthread', lock='semaphore', versio...\n", " version = '3.9.10 (main, Jan 17 2022, 00:00:00) \\n[GCC 11.2.1 20210728...\n", " version_info = sys.version_info(major=3, minor=9, micro=10, releaselev...\n", " warnoptions = []\n", "\n", "FILE\n", " (built-in)\n", "\n", "\n" ] } ], "source": [ "help(sys)" ] }, { "cell_type": "code", "execution_count": 31, "metadata": {}, "outputs": [], "source": [ "def eine_komplizierte_funktion(a, b):\n", " '''das ist eine sehr komplizierte funktion,\n", " die aber im endeffekt nix anderes macht, als a und b zusammenzuzaehlen\n", " und das ergebnis als wert hat.\n", " (sie tarnt sich also durch vergebliche komplexitaet)'''\n", " return a+b" ] }, { "cell_type": "code", "execution_count": 32, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "function" ] }, "execution_count": 32, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(eine_komplizierte_funktion)" ] }, { "cell_type": "code", "execution_count": 33, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'das ist eine sehr komplizierte funktion,\\n die aber im endeffekt nix anderes macht, als a und b zusammenzuzaehlen\\n und das ergebnis als wert hat.\\n (sie tarnt sich also durch vergebliche komplexitaet)'" ] }, "execution_count": 33, "metadata": {}, "output_type": "execute_result" } ], "source": [ "eine_komplizierte_funktion.__doc__" ] }, { "cell_type": "code", "execution_count": 34, "metadata": { "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on function eine_komplizierte_funktion in module __main__:\n", "\n", "eine_komplizierte_funktion(a, b)\n", " das ist eine sehr komplizierte funktion,\n", " die aber im endeffekt nix anderes macht, als a und b zusammenzuzaehlen\n", " und das ergebnis als wert hat.\n", " (sie tarnt sich also durch vergebliche komplexitaet)\n", "\n" ] } ], "source": [ "help(eine_komplizierte_funktion)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Sequentielle vs. Konstante Suchzeit" ] }, { "cell_type": "code", "execution_count": 35, "metadata": {}, "outputs": [], "source": [ "l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]" ] }, { "cell_type": "code", "execution_count": 36, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 36, "metadata": {}, "output_type": "execute_result" } ], "source": [ "2 in l" ] }, { "cell_type": "code", "execution_count": 37, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 37, "metadata": {}, "output_type": "execute_result" } ], "source": [ "12 in l" ] }, { "cell_type": "code", "execution_count": 38, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 38, "metadata": {}, "output_type": "execute_result" } ], "source": [ "666 in l" ] }, { "cell_type": "code", "execution_count": 39, "metadata": {}, "outputs": [], "source": [ "s = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}" ] }, { "cell_type": "code", "execution_count": 40, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 40, "metadata": {}, "output_type": "execute_result" } ], "source": [ "2 in s" ] }, { "cell_type": "code", "execution_count": 42, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 42, "metadata": {}, "output_type": "execute_result" } ], "source": [ "12 in s" ] }, { "cell_type": "code", "execution_count": 44, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 44, "metadata": {}, "output_type": "execute_result" } ], "source": [ "666 in s" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Exceptions" ] }, { "cell_type": "code", "execution_count": 46, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "666" ] }, "execution_count": 46, "metadata": {}, "output_type": "execute_result" } ], "source": [ "zahl_als_string = '666'\n", "zahl = int(zahl_als_string)\n", "zahl" ] }, { "cell_type": "code", "execution_count": 48, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "invalid literal for int() with base 10: 'bledsinn' \n" ] } ], "source": [ "try:\n", " zahl_als_string = 'bledsinn'\n", " int(zahl_als_string)\n", "except ValueError as e:\n", " print(e, type(e))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# ``for`` vs. ``while``, ``range()``" ] }, { "cell_type": "code", "execution_count": 54, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "hooray\n" ] } ], "source": [ "import random\n", "\n", "n_tries = 1\n", "while n_tries <= 6:\n", " eyes = random.randrange(1,7)\n", " if eyes == 6:\n", " print('hooray')\n", " break\n", " n_tries += 1\n", "else:\n", " print('lose!')" ] }, { "cell_type": "code", "execution_count": 83, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "lose!\n" ] } ], "source": [ "for try_no in range(1,7):\n", " eyes = random.randrange(1,7)\n", " if eyes == 6:\n", " print('hooray!')\n", " break\n", "else:\n", " print('lose!')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# String Methods (some)" ] }, { "cell_type": "code", "execution_count": 84, "metadata": {}, "outputs": [], "source": [ "line = ' '" ] }, { "cell_type": "code", "execution_count": 88, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 88, "metadata": {}, "output_type": "execute_result" } ], "source": [ "len(line) == 0" ] }, { "cell_type": "code", "execution_count": 89, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 89, "metadata": {}, "output_type": "execute_result" } ], "source": [ "line.isspace()" ] }, { "cell_type": "code", "execution_count": 91, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 91, "metadata": {}, "output_type": "execute_result" } ], "source": [ "line = ' \\r \\t \\n'\n", "line.isspace()" ] }, { "cell_type": "code", "execution_count": 92, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'abc'" ] }, "execution_count": 92, "metadata": {}, "output_type": "execute_result" } ], "source": [ "line = ' abc '\n", "line.strip()" ] }, { "cell_type": "code", "execution_count": 104, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'blahblahblah'" ] }, "execution_count": 104, "metadata": {}, "output_type": "execute_result" } ], "source": [ "line = 'blahblahblah\\n'\n", "line.strip()" ] }, { "cell_type": "code", "execution_count": 106, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'blahblahblah'" ] }, "execution_count": 106, "metadata": {}, "output_type": "execute_result" } ], "source": [ "line = ' blahblahblah \\t\\t\\r \\n'\n", "line.strip()" ] }, { "cell_type": "code", "execution_count": 108, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 108, "metadata": {}, "output_type": "execute_result" } ], "source": [ "line = '\\t \\r \\t\\n'\n", "line.isspace()" ] }, { "cell_type": "code", "execution_count": 111, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0" ] }, "execution_count": 111, "metadata": {}, "output_type": "execute_result" } ], "source": [ "line = line.strip()\n", "len(line)" ] }, { "cell_type": "code", "execution_count": 99, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "' abc'" ] }, "execution_count": 99, "metadata": {}, "output_type": "execute_result" } ], "source": [ "line = ' abc '\n", "line.rstrip()" ] }, { "cell_type": "code", "execution_count": 100, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "' abc'" ] }, "execution_count": 100, "metadata": {}, "output_type": "execute_result" } ], "source": [ "line = ' abc\\r\\t\\n'\n", "line.rstrip()" ] }, { "cell_type": "code", "execution_count": 101, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "' abc\\r\\t'" ] }, "execution_count": 101, "metadata": {}, "output_type": "execute_result" } ], "source": [ "line.rstrip('\\n')" ] }, { "cell_type": "code", "execution_count": 102, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "' abc\\r'" ] }, "execution_count": 102, "metadata": {}, "output_type": "execute_result" } ], "source": [ "line.rstrip('\\n\\t')" ] }, { "cell_type": "code", "execution_count": 103, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'c'" ] }, "execution_count": 103, "metadata": {}, "output_type": "execute_result" } ], "source": [ "line = 'cxyxyyyyxy'\n", "line.rstrip('xy')" ] }, { "cell_type": "code", "execution_count": 95, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "5" ] }, "execution_count": 95, "metadata": {}, "output_type": "execute_result" } ], "source": [ "line = ' # comment '\n", "line.find('#')" ] }, { "cell_type": "code", "execution_count": 97, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "' '" ] }, "execution_count": 97, "metadata": {}, "output_type": "execute_result" } ], "source": [ "line[:5]" ] }, { "cell_type": "code", "execution_count": 98, "metadata": { "scrolled": true }, "outputs": [ { "data": { "text/plain": [ "' '" ] }, "execution_count": 98, "metadata": {}, "output_type": "execute_result" } ], "source": [ "line[:line.find('#')]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# ``eval()``" ] }, { "cell_type": "code", "execution_count": 116, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "str" ] }, "execution_count": 116, "metadata": {}, "output_type": "execute_result" } ], "source": [ "table_str = '{\"eins\": 1, \"zwei\": 2}'\n", "type(table_str)" ] }, { "cell_type": "code", "execution_count": 117, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " string indices must be integers\n" ] } ], "source": [ "try:\n", " table_str[\"eins\"]\n", "except Exception as e:\n", " print(type(e), e)" ] }, { "cell_type": "code", "execution_count": 118, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'{'" ] }, "execution_count": 118, "metadata": {}, "output_type": "execute_result" } ], "source": [ "table_str[0]" ] }, { "cell_type": "code", "execution_count": 120, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "dict" ] }, "execution_count": 120, "metadata": {}, "output_type": "execute_result" } ], "source": [ "table_dict = eval(table_str)\n", "type(table_dict)" ] }, { "cell_type": "code", "execution_count": 122, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 122, "metadata": {}, "output_type": "execute_result" } ], "source": [ "table_dict[\"eins\"]" ] }, { "cell_type": "code", "execution_count": 123, "metadata": {}, "outputs": [], "source": [ "table_dict[\"drei\"] = 3" ] }, { "cell_type": "code", "execution_count": 124, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "3" ] }, "execution_count": 124, "metadata": {}, "output_type": "execute_result" } ], "source": [ "table_dict[\"drei\"]" ] }, { "cell_type": "code", "execution_count": 126, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'{\"eins\": 1, \"zwei\": 2}'" ] }, "execution_count": 126, "metadata": {}, "output_type": "execute_result" } ], "source": [ "table_str" ] }, { "cell_type": "code", "execution_count": 128, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "139769175732912" ] }, "execution_count": 128, "metadata": {}, "output_type": "execute_result" } ], "source": [ "id(table_str)" ] }, { "cell_type": "code", "execution_count": 129, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "139769175738624" ] }, "execution_count": 129, "metadata": {}, "output_type": "execute_result" } ], "source": [ "id(table_dict)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Geht auch fuer andere Datentypen!!**" ] }, { "cell_type": "code", "execution_count": 130, "metadata": {}, "outputs": [], "source": [ "satan_str = '666'" ] }, { "cell_type": "code", "execution_count": 132, "metadata": {}, "outputs": [], "source": [ "satan_int = eval(satan_str)" ] }, { "cell_type": "code", "execution_count": 134, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "666" ] }, "execution_count": 134, "metadata": {}, "output_type": "execute_result" } ], "source": [ "satan_int" ] }, { "cell_type": "code", "execution_count": 136, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " invalid syntax (, line 1)\n" ] } ], "source": [ "try:\n", " eval('if True: print(\"hallo\")')\n", "except Exception as e:\n", " print(type(e), e)" ] }, { "cell_type": "code", "execution_count": 137, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "hallo\n" ] } ], "source": [ "result_of_print = print('hallo')" ] }, { "cell_type": "code", "execution_count": 140, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "None\n" ] } ], "source": [ "print(result_of_print)" ] }, { "cell_type": "code", "execution_count": 143, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "hallo\n" ] } ], "source": [ "result_of_evald_print = eval('print(\"hallo\")')" ] }, { "cell_type": "code", "execution_count": 144, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "None\n" ] } ], "source": [ "print(result_of_evald_print)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# ``exec()``" ] }, { "cell_type": "code", "execution_count": 145, "metadata": {}, "outputs": [], "source": [ "code_str = \"\"\"\n", "for i in range(5):\n", " print(i)\n", "\"\"\"" ] }, { "cell_type": "code", "execution_count": 147, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "str" ] }, "execution_count": 147, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(code_str)" ] }, { "cell_type": "code", "execution_count": 149, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0\n", "1\n", "2\n", "3\n", "4\n" ] } ], "source": [ "exec(code_str)" ] }, { "cell_type": "code", "execution_count": 155, "metadata": {}, "outputs": [], "source": [ "compiled_code = compile(code_str, mode='exec', filename='woswasi.py')" ] }, { "cell_type": "code", "execution_count": 156, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "code" ] }, "execution_count": 156, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(compiled_code)" ] }, { "cell_type": "code", "execution_count": 158, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0\n", "1\n", "2\n", "3\n", "4\n" ] } ], "source": [ "exec(code)" ] }, { "cell_type": "code", "execution_count": 159, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "5\n" ] } ], "source": [ "if True: print(5)" ] }, { "cell_type": "code", "execution_count": 161, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "7" ] }, "execution_count": 161, "metadata": {}, "output_type": "execute_result" } ], "source": [ "7" ] }, { "cell_type": "code", "execution_count": 162, "metadata": {}, "outputs": [ { "data": { "text/plain": [ " at 0x7f1e91eb42f0, file \"woswasi.py\", line 2>" ] }, "execution_count": 162, "metadata": {}, "output_type": "execute_result" } ], "source": [ "code" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Iterator protocol" ] }, { "cell_type": "code", "execution_count": 165, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "range" ] }, "execution_count": 165, "metadata": {}, "output_type": "execute_result" } ], "source": [ "r = range(3)\n", "type(r)" ] }, { "cell_type": "code", "execution_count": 167, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "range_iterator" ] }, "execution_count": 167, "metadata": {}, "output_type": "execute_result" } ], "source": [ "it = iter(r)\n", "type(it)" ] }, { "cell_type": "code", "execution_count": 168, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0" ] }, "execution_count": 168, "metadata": {}, "output_type": "execute_result" } ], "source": [ "next(it)" ] }, { "cell_type": "code", "execution_count": 169, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 169, "metadata": {}, "output_type": "execute_result" } ], "source": [ "next(it)" ] }, { "cell_type": "code", "execution_count": 170, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "2" ] }, "execution_count": 170, "metadata": {}, "output_type": "execute_result" } ], "source": [ "next(it)" ] }, { "cell_type": "code", "execution_count": 172, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " \n" ] } ], "source": [ "try:\n", " next(it)\n", "except Exception as e:\n", " print(type(e), e)" ] }, { "cell_type": "code", "execution_count": 173, "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": 174, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "caro\n", "joerg\n", "johanna\n", "philipp\n" ] } ], "source": [ "for elem in ['caro', 'joerg', 'johanna', 'philipp']:\n", " print(elem)" ] }, { "cell_type": "code", "execution_count": 175, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0 caro\n", "1 joerg\n", "2 johanna\n", "3 philipp\n" ] } ], "source": [ "i = 0\n", "for elem in ['caro', 'joerg', 'johanna', 'philipp']:\n", " print(i, elem)\n", " i += 1" ] }, { "cell_type": "code", "execution_count": 176, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "(0, 'caro')\n", "(1, 'joerg')\n", "(2, 'johanna')\n", "(3, 'philipp')\n" ] } ], "source": [ "for elem in enumerate(['caro', 'joerg', 'johanna', 'philipp']):\n", " print(elem)" ] }, { "cell_type": "code", "execution_count": 179, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0 caro\n", "1 joerg\n", "2 johanna\n", "3 philipp\n" ] } ], "source": [ "for i, elem in enumerate(['caro', 'joerg', 'johanna', 'philipp']):\n", " print(i, elem)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Dictionary Iteration" ] }, { "cell_type": "code", "execution_count": 180, "metadata": {}, "outputs": [], "source": [ "user = {\n", " 'ID': 1,\n", " 'Firstname': 'Joerg',\n", " 'Lastname': 'Faschingbauer',\n", " 'Birth': '19.06.1966',\n", "}" ] }, { "cell_type": "code", "execution_count": 182, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "ID\n", "Firstname\n", "Lastname\n", "Birth\n" ] } ], "source": [ "for k in user:\n", " print(k)" ] }, { "cell_type": "code", "execution_count": 184, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "ID\n", "Firstname\n", "Lastname\n", "Birth\n" ] } ], "source": [ "for k in user.keys():\n", " print(k)" ] }, { "cell_type": "code", "execution_count": 186, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1\n", "Joerg\n", "Faschingbauer\n", "19.06.1966\n" ] } ], "source": [ "for v in user.values():\n", " print(v)" ] }, { "cell_type": "code", "execution_count": 188, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "('ID', 1)\n", "('Firstname', 'Joerg')\n", "('Lastname', 'Faschingbauer')\n", "('Birth', '19.06.1966')\n" ] } ], "source": [ "for elem in user.items():\n", " print(elem)" ] }, { "cell_type": "code", "execution_count": 189, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "key: ID , value: 1\n", "key: Firstname , value: Joerg\n", "key: Lastname , value: Faschingbauer\n", "key: Birth , value: 19.06.1966\n" ] } ], "source": [ "for elem in user.items():\n", " k = elem[0]\n", " v = elem[1]\n", " print('key:', k, ', value:', v)" ] }, { "cell_type": "code", "execution_count": 190, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "key: ID , value: 1\n", "key: Firstname , value: Joerg\n", "key: Lastname , value: Faschingbauer\n", "key: Birth , value: 19.06.1966\n" ] } ], "source": [ "for k, v in user.items():\n", " print('key:', k, ', value:', v)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Classes, Attributes, OO" ] }, { "cell_type": "code", "execution_count": 192, "metadata": {}, "outputs": [], "source": [ "class User:\n", " pass" ] }, { "cell_type": "code", "execution_count": 194, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "type" ] }, "execution_count": 194, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(User)" ] }, { "cell_type": "code", "execution_count": 195, "metadata": {}, "outputs": [], "source": [ "joerg = User()" ] }, { "cell_type": "code", "execution_count": 196, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "__main__.User" ] }, "execution_count": 196, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(joerg)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "``int`` is also **callable**" ] }, { "cell_type": "code", "execution_count": 197, "metadata": {}, "outputs": [], "source": [ "i = int()" ] }, { "cell_type": "code", "execution_count": 198, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0" ] }, "execution_count": 198, "metadata": {}, "output_type": "execute_result" } ], "source": [ "i" ] }, { "cell_type": "code", "execution_count": 199, "metadata": {}, "outputs": [], "source": [ "joerg.id = 1\n", "joerg.firstname = 'Jörg;DI'\n", "joerg.lastnmae = 'Faschingbauer'\n", "joerg.birth = '19.6.1966'" ] }, { "cell_type": "code", "execution_count": 201, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "<__main__.User at 0x7f1e8c0fe2e0>" ] }, "execution_count": 201, "metadata": {}, "output_type": "execute_result" } ], "source": [ "joerg" ] }, { "cell_type": "code", "execution_count": 202, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Jörg;DI'" ] }, "execution_count": 202, "metadata": {}, "output_type": "execute_result" } ], "source": [ "joerg.firstname" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Types and Instances" ] }, { "cell_type": "code", "execution_count": 203, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "int" ] }, "execution_count": 203, "metadata": {}, "output_type": "execute_result" } ], "source": [ "int" ] }, { "cell_type": "code", "execution_count": 204, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "print(int)" ] }, { "cell_type": "code", "execution_count": 205, "metadata": {}, "outputs": [], "source": [ "i = 666" ] }, { "cell_type": "code", "execution_count": 217, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "666" ] }, "execution_count": 217, "metadata": {}, "output_type": "execute_result" } ], "source": [ "i" ] }, { "cell_type": "code", "execution_count": 218, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0" ] }, "execution_count": 218, "metadata": {}, "output_type": "execute_result" } ], "source": [ "j = int()\n", "j" ] }, { "cell_type": "code", "execution_count": 236, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "666" ] }, "execution_count": 236, "metadata": {}, "output_type": "execute_result" } ], "source": [ "j = int(666)\n", "j" ] }, { "cell_type": "code", "execution_count": 238, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "666" ] }, "execution_count": 238, "metadata": {}, "output_type": "execute_result" } ], "source": [ "j = int('666')\n", "j" ] }, { "cell_type": "code", "execution_count": 226, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "666" ] }, "execution_count": 226, "metadata": {}, "output_type": "execute_result" } ], "source": [ "j = 666\n", "j" ] }, { "cell_type": "code", "execution_count": 240, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "15" ] }, "execution_count": 240, "metadata": {}, "output_type": "execute_result" } ], "source": [ "j = int('f', 16)\n", "j" ] }, { "cell_type": "code", "execution_count": 228, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['__abs__',\n", " '__add__',\n", " '__and__',\n", " '__bool__',\n", " '__ceil__',\n", " '__class__',\n", " '__delattr__',\n", " '__dir__',\n", " '__divmod__',\n", " '__doc__',\n", " '__eq__',\n", " '__float__',\n", " '__floor__',\n", " '__floordiv__',\n", " '__format__',\n", " '__ge__',\n", " '__getattribute__',\n", " '__getnewargs__',\n", " '__gt__',\n", " '__hash__',\n", " '__index__',\n", " '__init__',\n", " '__init_subclass__',\n", " '__int__',\n", " '__invert__',\n", " '__le__',\n", " '__lshift__',\n", " '__lt__',\n", " '__mod__',\n", " '__mul__',\n", " '__ne__',\n", " '__neg__',\n", " '__new__',\n", " '__or__',\n", " '__pos__',\n", " '__pow__',\n", " '__radd__',\n", " '__rand__',\n", " '__rdivmod__',\n", " '__reduce__',\n", " '__reduce_ex__',\n", " '__repr__',\n", " '__rfloordiv__',\n", " '__rlshift__',\n", " '__rmod__',\n", " '__rmul__',\n", " '__ror__',\n", " '__round__',\n", " '__rpow__',\n", " '__rrshift__',\n", " '__rshift__',\n", " '__rsub__',\n", " '__rtruediv__',\n", " '__rxor__',\n", " '__setattr__',\n", " '__sizeof__',\n", " '__str__',\n", " '__sub__',\n", " '__subclasshook__',\n", " '__truediv__',\n", " '__trunc__',\n", " '__xor__',\n", " 'as_integer_ratio',\n", " 'bit_length',\n", " 'conjugate',\n", " 'denominator',\n", " 'from_bytes',\n", " 'imag',\n", " 'numerator',\n", " 'real',\n", " 'to_bytes']" ] }, "execution_count": 228, "metadata": {}, "output_type": "execute_result" } ], "source": [ "dir(j)" ] }, { "cell_type": "code", "execution_count": 230, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 230, "metadata": {}, "output_type": "execute_result" } ], "source": [ "j.__bool__()" ] }, { "cell_type": "code", "execution_count": 231, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 231, "metadata": {}, "output_type": "execute_result" } ], "source": [ "bool(j)" ] }, { "cell_type": "code", "execution_count": 223, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'0x7f1e8c0b3130'" ] }, "execution_count": 223, "metadata": {}, "output_type": "execute_result" } ], "source": [ "hex(id(j))" ] }, { "cell_type": "code", "execution_count": 234, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "print(type(i))" ] }, { "cell_type": "code", "execution_count": 235, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "int" ] }, "execution_count": 235, "metadata": {}, "output_type": "execute_result" } ], "source": [ "i.__class__" ] }, { "cell_type": "code", "execution_count": 212, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[42, 666]" ] }, "execution_count": 212, "metadata": {}, "output_type": "execute_result" } ], "source": [ "int_liste = []\n", "int_liste.append(42)\n", "int_liste.append(666)\n", "int_liste" ] }, { "cell_type": "code", "execution_count": 213, "metadata": {}, "outputs": [], "source": [ "class User:\n", " pass" ] }, { "cell_type": "code", "execution_count": 224, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "<__main__.User object at 0x7f1e8c0fe340>\n", "\n" ] } ], "source": [ "u = User()\n", "print(u)\n", "print(type(u))" ] }, { "cell_type": "code", "execution_count": 232, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['__class__',\n", " '__delattr__',\n", " '__dict__',\n", " '__dir__',\n", " '__doc__',\n", " '__eq__',\n", " '__format__',\n", " '__ge__',\n", " '__getattribute__',\n", " '__gt__',\n", " '__hash__',\n", " '__init__',\n", " '__init_subclass__',\n", " '__le__',\n", " '__lt__',\n", " '__module__',\n", " '__ne__',\n", " '__new__',\n", " '__reduce__',\n", " '__reduce_ex__',\n", " '__repr__',\n", " '__setattr__',\n", " '__sizeof__',\n", " '__str__',\n", " '__subclasshook__',\n", " '__weakref__']" ] }, "execution_count": 232, "metadata": {}, "output_type": "execute_result" } ], "source": [ "dir(u)" ] }, { "cell_type": "code", "execution_count": 241, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "print(u.__class__)" ] }, { "cell_type": "code", "execution_count": 242, "metadata": {}, "outputs": [], "source": [ "class User:\n", " def __init__(self, uid):\n", " pass" ] }, { "cell_type": "code", "execution_count": 244, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " __init__() missing 1 required positional argument: 'userid'\n" ] } ], "source": [ "try:\n", " u = User()\n", "except Exception as e:\n", " print(type(e), e)" ] }, { "cell_type": "code", "execution_count": 246, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "<__main__.User object at 0x7f1e8c0fe760>\n" ] } ], "source": [ "satan = User(666)\n", "print(satan)" ] }, { "cell_type": "code", "execution_count": 248, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " 'User' object has no attribute 'id'\n" ] } ], "source": [ "try:\n", " satan.uid\n", "except Exception as e:\n", " print(type(e), e)" ] }, { "cell_type": "code", "execution_count": 251, "metadata": {}, "outputs": [], "source": [ "class User:\n", " def __init__(self, uid):\n", " self.uid = uid" ] }, { "cell_type": "code", "execution_count": 252, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "42" ] }, "execution_count": 252, "metadata": {}, "output_type": "execute_result" } ], "source": [ "u = User(42)\n", "u.uid" ] }, { "cell_type": "code", "execution_count": 253, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0" ] }, "execution_count": 253, "metadata": {}, "output_type": "execute_result" } ], "source": [ "u = User(0)\n", "u.uid" ] }, { "cell_type": "code", "execution_count": 254, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "-666" ] }, "execution_count": 254, "metadata": {}, "output_type": "execute_result" } ], "source": [ "u = User(-666)\n", "u.uid" ] }, { "cell_type": "code", "execution_count": 255, "metadata": {}, "outputs": [], "source": [ "class User:\n", " def __init__(self, uid):\n", " assert uid > 0\n", " self.uid = uid" ] }, { "cell_type": "code", "execution_count": 257, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " \n" ] } ], "source": [ "try:\n", " u = User(0)\n", "except Exception as e:\n", " print(type(e), e)" ] }, { "cell_type": "code", "execution_count": 258, "metadata": {}, "outputs": [], "source": [ "u1 = User(1)\n", "u2 = User(1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Metaprogramming? Types? What is a Type?" ] }, { "cell_type": "code", "execution_count": 259, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "u = User(42)\n", "print(type(u))" ] }, { "cell_type": "code", "execution_count": 260, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "type_of_user = u.__class__\n", "print(type_of_user)" ] }, { "cell_type": "code", "execution_count": 264, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "print(type(type_of_user))" ] }, { "cell_type": "code", "execution_count": 266, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['__class__',\n", " '__delattr__',\n", " '__dict__',\n", " '__dir__',\n", " '__doc__',\n", " '__eq__',\n", " '__format__',\n", " '__ge__',\n", " '__getattribute__',\n", " '__gt__',\n", " '__hash__',\n", " '__init__',\n", " '__init_subclass__',\n", " '__le__',\n", " '__lt__',\n", " '__module__',\n", " '__ne__',\n", " '__new__',\n", " '__reduce__',\n", " '__reduce_ex__',\n", " '__repr__',\n", " '__setattr__',\n", " '__sizeof__',\n", " '__str__',\n", " '__subclasshook__',\n", " '__weakref__']" ] }, "execution_count": 266, "metadata": {}, "output_type": "execute_result" } ], "source": [ "dir(type_of_user)" ] }, { "cell_type": "code", "execution_count": 267, "metadata": {}, "outputs": [], "source": [ "class User:\n", " def __init__(self, uid, firstname, lastname, birth):\n", " assert uid > 0\n", " self.uid = uid\n", " self.firstname = firstname\n", " self.lastname = lastname\n", " self.birth = birth\n", " " ] }, { "cell_type": "code", "execution_count": 269, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "print(type(User))" ] }, { "cell_type": "code", "execution_count": 272, "metadata": {}, "outputs": [], "source": [ "def ctor(self, uid, firstname, lastname, birth):\n", " assert uid > 0\n", " self.uid = uid\n", " self.firstname = firstname\n", " self.lastname = lastname\n", " self.birth = birth\n", "def blah(self):\n", " self.firstname = self.firstname[::-1]\n", " self.lastname = self.lastname[::-1]" ] }, { "cell_type": "code", "execution_count": 274, "metadata": {}, "outputs": [], "source": [ "User = type('User', (), {'__init__': ctor, 'scramble': blah})" ] }, { "cell_type": "code", "execution_count": 276, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "type" ] }, "execution_count": 276, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(User)" ] }, { "cell_type": "code", "execution_count": 277, "metadata": {}, "outputs": [], "source": [ "u = User(1, 'Hansjörg', 'Faschingbauer', '19.06.1966')" ] }, { "cell_type": "code", "execution_count": 279, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 279, "metadata": {}, "output_type": "execute_result" } ], "source": [ "u.uid" ] }, { "cell_type": "code", "execution_count": 280, "metadata": {}, "outputs": [], "source": [ "u.scramble()" ] }, { "cell_type": "code", "execution_count": 281, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'gröjsnaH'" ] }, "execution_count": 281, "metadata": {}, "output_type": "execute_result" } ], "source": [ "u.firstname" ] }, { "cell_type": "code", "execution_count": 282, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Hansjörg'" ] }, "execution_count": 282, "metadata": {}, "output_type": "execute_result" } ], "source": [ "u.scramble()\n", "u.firstname" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Is the same as (recommended):" ] }, { "cell_type": "code", "execution_count": 283, "metadata": {}, "outputs": [], "source": [ "class User:\n", " def __init__(self, uid, firstname, lastname, birth):\n", " assert uid > 0\n", " self.uid = uid\n", " self.firstname = firstname\n", " self.lastname = lastname\n", " self.birth = birth\n", " def scramble(self):\n", " self.firstname = self.firstname[::-1]\n", " self.lastname = self.lastname[::-1]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Another way to dynamically create types: ``exec()``" ] }, { "cell_type": "code", "execution_count": 285, "metadata": {}, "outputs": [], "source": [ "class_str = '''\n", "class User:\n", " def __init__(self, uid, firstname, lastname, birth):\n", " assert uid > 0\n", " self.uid = uid\n", " self.firstname = firstname\n", " self.lastname = lastname\n", " self.birth = birth\n", " def scramble(self):\n", " self.firstname = self.firstname[::-1]\n", " self.lastname = self.lastname[::-1]\n", "'''" ] }, { "cell_type": "code", "execution_count": 286, "metadata": {}, "outputs": [], "source": [ "context = {}\n", "exec(class_str, context)" ] }, { "cell_type": "code", "execution_count": 287, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "print(context['User'])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# OO Everywhere" ] }, { "cell_type": "code", "execution_count": 299, "metadata": {}, "outputs": [], "source": [ "s = 'hallo'" ] }, { "cell_type": "code", "execution_count": 301, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "str" ] }, "execution_count": 301, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(s)" ] }, { "cell_type": "code", "execution_count": 303, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "2" ] }, "execution_count": 303, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s.find('ll')" ] }, { "cell_type": "code", "execution_count": 304, "metadata": {}, "outputs": [], "source": [ "d = {\n", " 1: User(1, 'Joerg', 'Faschingbauer', '19.6.1966'),\n", " 2: User(2, 'Caro', 'Faschingbauer', '25.4.1997'),\n", " }" ] }, { "cell_type": "code", "execution_count": 305, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "dict" ] }, "execution_count": 305, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(d)" ] }, { "cell_type": "code", "execution_count": 306, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "<__main__.User at 0x7f1e8c1c2e50>" ] }, "execution_count": 306, "metadata": {}, "output_type": "execute_result" } ], "source": [ "d[1]" ] }, { "cell_type": "code", "execution_count": 308, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "<__main__.User at 0x7f1e8c1c2e50>" ] }, "execution_count": 308, "metadata": {}, "output_type": "execute_result" } ], "source": [ "d.get(1)" ] }, { "cell_type": "code", "execution_count": 309, "metadata": {}, "outputs": [], "source": [ "d['joleckmi'] = ['jo', 'oida', 666]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Dictionary Operations" ] }, { "cell_type": "code", "execution_count": 310, "metadata": {}, "outputs": [], "source": [ "d = {\n", " '19.6.1966': 2,\n", " '1.1.1900': 1\n", "}" ] }, { "cell_type": "code", "execution_count": 317, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2\n" ] } ], "source": [ "counter = d.get('19.6.1966')\n", "print(counter)" ] }, { "cell_type": "code", "execution_count": 318, "metadata": {}, "outputs": [], "source": [ "d['19.6.1966'] = counter + 1" ] }, { "cell_type": "code", "execution_count": 314, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "None\n" ] } ], "source": [ "counter = d.get('25.4.1997')\n", "print(counter)" ] }, { "cell_type": "code", "execution_count": 316, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " '25.4.1997'\n" ] } ], "source": [ "try:\n", " d['25.4.1997']\n", "except Exception as e:\n", " print(type(e), e)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# ``collections.defaultdict``" ] }, { "cell_type": "code", "execution_count": 319, "metadata": {}, "outputs": [], "source": [ "from collections import defaultdict" ] }, { "cell_type": "code", "execution_count": 320, "metadata": {}, "outputs": [], "source": [ "counters = defaultdict(int)" ] }, { "cell_type": "code", "execution_count": 321, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0" ] }, "execution_count": 321, "metadata": {}, "output_type": "execute_result" } ], "source": [ "int()" ] }, { "cell_type": "code", "execution_count": 322, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0" ] }, "execution_count": 322, "metadata": {}, "output_type": "execute_result" } ], "source": [ "counters['19.6.1966']" ] }, { "cell_type": "code", "execution_count": 323, "metadata": {}, "outputs": [], "source": [ "counters['1.1.1900'] += 1" ] }, { "cell_type": "code", "execution_count": 324, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 324, "metadata": {}, "output_type": "execute_result" } ], "source": [ "counters['1.1.1900']" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "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.10" } }, "nbformat": 4, "nbformat_minor": 4 }