{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Hello World" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello World\n" ] } ], "source": [ "print('Hello World')" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Mississippi\n" ] } ], "source": [ "s = 'Mississippi'\n", "print(s)" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Mississippi'" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "2" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s.count('ss')" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "2" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s.index('ss')" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [], "source": [ "import json" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "d = {'eins': 1,\n", " 'zwei': 2}\n", "d['eins']" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [], "source": [ "d_as_str = json.dumps(d)" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'{\"eins\": 1, \"zwei\": 2}'" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "d_as_str" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [], "source": [ "received_d = json.loads(d_as_str)" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'eins': 1, 'zwei': 2}" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "received_d" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [], "source": [ "import subprocess" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "total 160\n", "-rw-rw-r--. 1 jfasch jfasch 4926 Mar 30 10:57 index.rst\n", "-rw-rw-r--. 1 jfasch jfasch 1939 Mar 1 17:00 index.rst.~1~\n", "-rw-rw-r--. 1 jfasch jfasch 145415 Mar 30 11:16 Notebook.ipynb\n", "-rw-rw-r--. 1 jfasch jfasch 72 Mar 1 16:38 notebook-wrapper.rst\n" ] }, { "data": { "text/plain": [ "CompletedProcess(args=['ls', '-l'], returncode=0)" ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "subprocess.run(['ls', '-l'])" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [], "source": [ "i = 42" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "42\n" ] } ], "source": [ "print(i)" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "int" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(i)" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [], "source": [ "i = [1, 2, 3]" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "list" ] }, "execution_count": 18, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(i)" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [], "source": [ "f = open('/etc/passwd')" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "root\n", "bin\n", "daemon\n", "adm\n", "lp\n", "sync\n", "shutdown\n", "halt\n", "mail\n", "operator\n", "games\n", "ftp\n", "nobody\n", "apache\n", "systemd-network\n", "systemd-coredump\n", "systemd-resolve\n", "systemd-oom\n", "systemd-timesync\n", "tss\n", "dbus\n", "polkitd\n", "avahi\n", "unbound\n", "dnsmasq\n", "nm-openconnect\n", "usbmuxd\n", "gluster\n", "rtkit\n", "pipewire\n", "geoclue\n", "chrony\n", "saslauth\n", "radvd\n", "rpc\n", "qemu\n", "openvpn\n", "nm-openvpn\n", "colord\n", "rpcuser\n", "abrt\n", "flatpak\n", "gdm\n", "gnome-initial-setup\n", "vboxadd\n", "sshd\n", "tcpdump\n", "jfasch\n", "mosquitto\n", "someone-else\n" ] } ], "source": [ "for line in f:\n", " line = line.rstrip('\\n')\n", " fields = line.split(':')\n", " print(fields[0])" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Mississippi'" ] }, "execution_count": 21, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on class str in module builtins:\n", "\n", "class str(object)\n", " | str(object='') -> str\n", " | str(bytes_or_buffer[, encoding[, errors]]) -> str\n", " | \n", " | Create a new string object from the given object. If encoding or\n", " | errors is specified, then the object must expose a data buffer\n", " | that will be decoded using the given encoding and error handler.\n", " | Otherwise, returns the result of object.__str__() (if defined)\n", " | or repr(object).\n", " | encoding defaults to sys.getdefaultencoding().\n", " | errors defaults to 'strict'.\n", " | \n", " | Methods defined here:\n", " | \n", " | __add__(self, value, /)\n", " | Return self+value.\n", " | \n", " | __contains__(self, key, /)\n", " | Return key in self.\n", " | \n", " | __eq__(self, value, /)\n", " | Return self==value.\n", " | \n", " | __format__(self, format_spec, /)\n", " | Return a formatted version of the string as described by format_spec.\n", " | \n", " | __ge__(self, value, /)\n", " | Return self>=value.\n", " | \n", " | __getattribute__(self, name, /)\n", " | Return getattr(self, name).\n", " | \n", " | __getitem__(self, key, /)\n", " | Return self[key].\n", " | \n", " | __getnewargs__(...)\n", " | \n", " | __gt__(self, value, /)\n", " | Return self>value.\n", " | \n", " | __hash__(self, /)\n", " | Return hash(self).\n", " | \n", " | __iter__(self, /)\n", " | Implement iter(self).\n", " | \n", " | __le__(self, value, /)\n", " | Return self<=value.\n", " | \n", " | __len__(self, /)\n", " | Return len(self).\n", " | \n", " | __lt__(self, value, /)\n", " | Return self int\n", " | \n", " | Return the number of non-overlapping occurrences of substring sub in\n", " | string S[start:end]. Optional arguments start and end are\n", " | interpreted as in slice notation.\n", " | \n", " | encode(self, /, encoding='utf-8', errors='strict')\n", " | Encode the string using the codec registered for encoding.\n", " | \n", " | encoding\n", " | The encoding in which to encode the string.\n", " | errors\n", " | The error handling scheme to use for encoding errors.\n", " | The default is 'strict' meaning that encoding errors raise a\n", " | UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n", " | 'xmlcharrefreplace' as well as any other name registered with\n", " | codecs.register_error that can handle UnicodeEncodeErrors.\n", " | \n", " | endswith(...)\n", " | S.endswith(suffix[, start[, end]]) -> bool\n", " | \n", " | Return True if S ends with the specified suffix, False otherwise.\n", " | With optional start, test S beginning at that position.\n", " | With optional end, stop comparing S at that position.\n", " | suffix can also be a tuple of strings to try.\n", " | \n", " | expandtabs(self, /, tabsize=8)\n", " | Return a copy where all tab characters are expanded using spaces.\n", " | \n", " | If tabsize is not given, a tab size of 8 characters is assumed.\n", " | \n", " | find(...)\n", " | S.find(sub[, start[, end]]) -> int\n", " | \n", " | Return the lowest index in S where substring sub is found,\n", " | such that sub is contained within S[start:end]. Optional\n", " | arguments start and end are interpreted as in slice notation.\n", " | \n", " | Return -1 on failure.\n", " | \n", " | format(...)\n", " | S.format(*args, **kwargs) -> str\n", " | \n", " | Return a formatted version of S, using substitutions from args and kwargs.\n", " | The substitutions are identified by braces ('{' and '}').\n", " | \n", " | format_map(...)\n", " | S.format_map(mapping) -> str\n", " | \n", " | Return a formatted version of S, using substitutions from mapping.\n", " | The substitutions are identified by braces ('{' and '}').\n", " | \n", " | index(...)\n", " | S.index(sub[, start[, end]]) -> int\n", " | \n", " | Return the lowest index in S where substring sub is found,\n", " | such that sub is contained within S[start:end]. Optional\n", " | arguments start and end are interpreted as in slice notation.\n", " | \n", " | Raises ValueError when the substring is not found.\n", " | \n", " | isalnum(self, /)\n", " | Return True if the string is an alpha-numeric string, False otherwise.\n", " | \n", " | A string is alpha-numeric if all characters in the string are alpha-numeric and\n", " | there is at least one character in the string.\n", " | \n", " | isalpha(self, /)\n", " | Return True if the string is an alphabetic string, False otherwise.\n", " | \n", " | A string is alphabetic if all characters in the string are alphabetic and there\n", " | is at least one character in the string.\n", " | \n", " | isascii(self, /)\n", " | Return True if all characters in the string are ASCII, False otherwise.\n", " | \n", " | ASCII characters have code points in the range U+0000-U+007F.\n", " | Empty string is ASCII too.\n", " | \n", " | isdecimal(self, /)\n", " | Return True if the string is a decimal string, False otherwise.\n", " | \n", " | A string is a decimal string if all characters in the string are decimal and\n", " | there is at least one character in the string.\n", " | \n", " | isdigit(self, /)\n", " | Return True if the string is a digit string, False otherwise.\n", " | \n", " | A string is a digit string if all characters in the string are digits and there\n", " | is at least one character in the string.\n", " | \n", " | isidentifier(self, /)\n", " | Return True if the string is a valid Python identifier, False otherwise.\n", " | \n", " | Call keyword.iskeyword(s) to test whether string s is a reserved identifier,\n", " | such as \"def\" or \"class\".\n", " | \n", " | islower(self, /)\n", " | Return True if the string is a lowercase string, False otherwise.\n", " | \n", " | A string is lowercase if all cased characters in the string are lowercase and\n", " | there is at least one cased character in the string.\n", " | \n", " | isnumeric(self, /)\n", " | Return True if the string is a numeric string, False otherwise.\n", " | \n", " | A string is numeric if all characters in the string are numeric and there is at\n", " | least one character in the string.\n", " | \n", " | isprintable(self, /)\n", " | Return True if the string is printable, False otherwise.\n", " | \n", " | A string is printable if all of its characters are considered printable in\n", " | repr() or if it is empty.\n", " | \n", " | isspace(self, /)\n", " | Return True if the string is a whitespace string, False otherwise.\n", " | \n", " | A string is whitespace if all characters in the string are whitespace and there\n", " | is at least one character in the string.\n", " | \n", " | istitle(self, /)\n", " | Return True if the string is a title-cased string, False otherwise.\n", " | \n", " | In a title-cased string, upper- and title-case characters may only\n", " | follow uncased characters and lowercase characters only cased ones.\n", " | \n", " | isupper(self, /)\n", " | Return True if the string is an uppercase string, False otherwise.\n", " | \n", " | A string is uppercase if all cased characters in the string are uppercase and\n", " | there is at least one cased character in the string.\n", " | \n", " | join(self, iterable, /)\n", " | Concatenate any number of strings.\n", " | \n", " | The string whose method is called is inserted in between each given string.\n", " | The result is returned as a new string.\n", " | \n", " | Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'\n", " | \n", " | ljust(self, width, fillchar=' ', /)\n", " | Return a left-justified string of length width.\n", " | \n", " | Padding is done using the specified fill character (default is a space).\n", " | \n", " | lower(self, /)\n", " | Return a copy of the string converted to lowercase.\n", " | \n", " | lstrip(self, chars=None, /)\n", " | Return a copy of the string with leading whitespace removed.\n", " | \n", " | If chars is given and not None, remove characters in chars instead.\n", " | \n", " | partition(self, sep, /)\n", " | Partition the string into three parts using the given separator.\n", " | \n", " | This will search for the separator in the string. If the separator is found,\n", " | returns a 3-tuple containing the part before the separator, the separator\n", " | itself, and the part after it.\n", " | \n", " | If the separator is not found, returns a 3-tuple containing the original string\n", " | and two empty strings.\n", " | \n", " | removeprefix(self, prefix, /)\n", " | Return a str with the given prefix string removed if present.\n", " | \n", " | If the string starts with the prefix string, return string[len(prefix):].\n", " | Otherwise, return a copy of the original string.\n", " | \n", " | removesuffix(self, suffix, /)\n", " | Return a str with the given suffix string removed if present.\n", " | \n", " | If the string ends with the suffix string and that suffix is not empty,\n", " | return string[:-len(suffix)]. Otherwise, return a copy of the original\n", " | string.\n", " | \n", " | replace(self, old, new, count=-1, /)\n", " | Return a copy with all occurrences of substring old replaced by new.\n", " | \n", " | count\n", " | Maximum number of occurrences to replace.\n", " | -1 (the default value) means replace all occurrences.\n", " | \n", " | If the optional argument count is given, only the first count occurrences are\n", " | replaced.\n", " | \n", " | rfind(...)\n", " | S.rfind(sub[, start[, end]]) -> int\n", " | \n", " | Return the highest index in S where substring sub is found,\n", " | such that sub is contained within S[start:end]. Optional\n", " | arguments start and end are interpreted as in slice notation.\n", " | \n", " | Return -1 on failure.\n", " | \n", " | rindex(...)\n", " | S.rindex(sub[, start[, end]]) -> int\n", " | \n", " | Return the highest index in S where substring sub is found,\n", " | such that sub is contained within S[start:end]. Optional\n", " | arguments start and end are interpreted as in slice notation.\n", " | \n", " | Raises ValueError when the substring is not found.\n", " | \n", " | rjust(self, width, fillchar=' ', /)\n", " | Return a right-justified string of length width.\n", " | \n", " | Padding is done using the specified fill character (default is a space).\n", " | \n", " | rpartition(self, sep, /)\n", " | Partition the string into three parts using the given separator.\n", " | \n", " | This will search for the separator in the string, starting at the end. If\n", " | the separator is found, returns a 3-tuple containing the part before the\n", " | separator, the separator itself, and the part after it.\n", " | \n", " | If the separator is not found, returns a 3-tuple containing two empty strings\n", " | and the original string.\n", " | \n", " | rsplit(self, /, sep=None, maxsplit=-1)\n", " | Return a list of the words in the string, using sep as the delimiter string.\n", " | \n", " | sep\n", " | The delimiter according which to split the string.\n", " | None (the default value) means split according to any whitespace,\n", " | and discard empty strings from the result.\n", " | maxsplit\n", " | Maximum number of splits to do.\n", " | -1 (the default value) means no limit.\n", " | \n", " | Splits are done starting at the end of the string and working to the front.\n", " | \n", " | rstrip(self, chars=None, /)\n", " | Return a copy of the string with trailing whitespace removed.\n", " | \n", " | If chars is given and not None, remove characters in chars instead.\n", " | \n", " | split(self, /, sep=None, maxsplit=-1)\n", " | Return a list of the words in the string, using sep as the delimiter string.\n", " | \n", " | sep\n", " | The delimiter according which to split the string.\n", " | None (the default value) means split according to any whitespace,\n", " | and discard empty strings from the result.\n", " | maxsplit\n", " | Maximum number of splits to do.\n", " | -1 (the default value) means no limit.\n", " | \n", " | splitlines(self, /, keepends=False)\n", " | Return a list of the lines in the string, breaking at line boundaries.\n", " | \n", " | Line breaks are not included in the resulting list unless keepends is given and\n", " | true.\n", " | \n", " | startswith(...)\n", " | S.startswith(prefix[, start[, end]]) -> bool\n", " | \n", " | Return True if S starts with the specified prefix, False otherwise.\n", " | With optional start, test S beginning at that position.\n", " | With optional end, stop comparing S at that position.\n", " | prefix can also be a tuple of strings to try.\n", " | \n", " | strip(self, chars=None, /)\n", " | Return a copy of the string with leading and trailing whitespace removed.\n", " | \n", " | If chars is given and not None, remove characters in chars instead.\n", " | \n", " | swapcase(self, /)\n", " | Convert uppercase characters to lowercase and lowercase characters to uppercase.\n", " | \n", " | title(self, /)\n", " | Return a version of the string where each word is titlecased.\n", " | \n", " | More specifically, words start with uppercased characters and all remaining\n", " | cased characters have lower case.\n", " | \n", " | translate(self, table, /)\n", " | Replace each character in the string using the given translation table.\n", " | \n", " | table\n", " | Translation table, which must be a mapping of Unicode ordinals to\n", " | Unicode ordinals, strings, or None.\n", " | \n", " | The table must implement lookup/indexing via __getitem__, for instance a\n", " | dictionary or list. If this operation raises LookupError, the character is\n", " | left untouched. Characters mapped to None are deleted.\n", " | \n", " | upper(self, /)\n", " | Return a copy of the string converted to uppercase.\n", " | \n", " | zfill(self, width, /)\n", " | Pad a numeric string with zeros on the left, to fill a field of the given width.\n", " | \n", " | The string is never truncated.\n", " | \n", " | ----------------------------------------------------------------------\n", " | Static methods defined here:\n", " | \n", " | __new__(*args, **kwargs) from builtins.type\n", " | Create and return a new object. See help(type) for accurate signature.\n", " | \n", " | maketrans(...)\n", " | Return a translation table usable for str.translate().\n", " | \n", " | If there is only one argument, it must be a dictionary mapping Unicode\n", " | ordinals (integers) or characters to Unicode ordinals, strings or None.\n", " | Character keys will be then converted to ordinals.\n", " | If there are two arguments, they must be strings of equal length, and\n", " | in the resulting dictionary, each character in x will be mapped to the\n", " | character at the same position in y. If there is a third argument, it\n", " | must be a string, whose characters will be mapped to None in the result.\n", "\n" ] } ], "source": [ "help(str)" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "' Mississippi '" ] }, "execution_count": 23, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s.center(50)" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [], "source": [ "def add(l, r):\n", " '''\n", " Diese extrem komplexe Funktion nimmt die beiden Parameter l und r her,\n", " und bildet mit einem numerischen Algorithmus die Summe aus beiden.\n", " \n", " Diese Summe ist dann der Wert des Aufrufs.\n", " '''\n", " return l+r" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "3" ] }, "execution_count": 25, "metadata": {}, "output_type": "execute_result" } ], "source": [ "add(1, 2)" ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'\\n Diese extrem komplexe Funktion nimmt die beiden Parameter l und r her,\\n und bildet mit einem numerischen Algorithmus die Summe aus beiden.\\n \\n Diese Summe ist dann der Wert des Aufrufs.\\n '" ] }, "execution_count": 26, "metadata": {}, "output_type": "execute_result" } ], "source": [ "add.__doc__" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on function add in module __main__:\n", "\n", "add(l, r)\n", " Diese extrem komplexe Funktion nimmt die beiden Parameter l und r her,\n", " und bildet mit einem numerischen Algorithmus die Summe aus beiden.\n", " \n", " Diese Summe ist dann der Wert des Aufrufs.\n", "\n" ] } ], "source": [ "help(add)" ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "" ] }, "execution_count": 28, "metadata": {}, "output_type": "execute_result" } ], "source": [ "json" ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on package json:\n", "\n", "NAME\n", " json\n", "\n", "MODULE REFERENCE\n", " https://docs.python.org/3.9/library/json\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", " JSON (JavaScript Object Notation) is a subset of\n", " JavaScript syntax (ECMA-262 3rd edition) used as a lightweight data\n", " interchange format.\n", " \n", " :mod:`json` exposes an API familiar to users of the standard library\n", " :mod:`marshal` and :mod:`pickle` modules. It is derived from a\n", " version of the externally maintained simplejson library.\n", " \n", " Encoding basic Python object hierarchies::\n", " \n", " >>> import json\n", " >>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])\n", " '[\"foo\", {\"bar\": [\"baz\", null, 1.0, 2]}]'\n", " >>> print(json.dumps(\"\\\"foo\\bar\"))\n", " \"\\\"foo\\bar\"\n", " >>> print(json.dumps('\\u1234'))\n", " \"\\u1234\"\n", " >>> print(json.dumps('\\\\'))\n", " \"\\\\\"\n", " >>> print(json.dumps({\"c\": 0, \"b\": 0, \"a\": 0}, sort_keys=True))\n", " {\"a\": 0, \"b\": 0, \"c\": 0}\n", " >>> from io import StringIO\n", " >>> io = StringIO()\n", " >>> json.dump(['streaming API'], io)\n", " >>> io.getvalue()\n", " '[\"streaming API\"]'\n", " \n", " Compact encoding::\n", " \n", " >>> import json\n", " >>> mydict = {'4': 5, '6': 7}\n", " >>> json.dumps([1,2,3,mydict], separators=(',', ':'))\n", " '[1,2,3,{\"4\":5,\"6\":7}]'\n", " \n", " Pretty printing::\n", " \n", " >>> import json\n", " >>> print(json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4))\n", " {\n", " \"4\": 5,\n", " \"6\": 7\n", " }\n", " \n", " Decoding JSON::\n", " \n", " >>> import json\n", " >>> obj = ['foo', {'bar': ['baz', None, 1.0, 2]}]\n", " >>> json.loads('[\"foo\", {\"bar\":[\"baz\", null, 1.0, 2]}]') == obj\n", " True\n", " >>> json.loads('\"\\\\\"foo\\\\bar\"') == '\"foo\\x08ar'\n", " True\n", " >>> from io import StringIO\n", " >>> io = StringIO('[\"streaming API\"]')\n", " >>> json.load(io)[0] == 'streaming API'\n", " True\n", " \n", " Specializing JSON object decoding::\n", " \n", " >>> import json\n", " >>> def as_complex(dct):\n", " ... if '__complex__' in dct:\n", " ... return complex(dct['real'], dct['imag'])\n", " ... return dct\n", " ...\n", " >>> json.loads('{\"__complex__\": true, \"real\": 1, \"imag\": 2}',\n", " ... object_hook=as_complex)\n", " (1+2j)\n", " >>> from decimal import Decimal\n", " >>> json.loads('1.1', parse_float=Decimal) == Decimal('1.1')\n", " True\n", " \n", " Specializing JSON object encoding::\n", " \n", " >>> import json\n", " >>> def encode_complex(obj):\n", " ... if isinstance(obj, complex):\n", " ... return [obj.real, obj.imag]\n", " ... raise TypeError(f'Object of type {obj.__class__.__name__} '\n", " ... f'is not JSON serializable')\n", " ...\n", " >>> json.dumps(2 + 1j, default=encode_complex)\n", " '[2.0, 1.0]'\n", " >>> json.JSONEncoder(default=encode_complex).encode(2 + 1j)\n", " '[2.0, 1.0]'\n", " >>> ''.join(json.JSONEncoder(default=encode_complex).iterencode(2 + 1j))\n", " '[2.0, 1.0]'\n", " \n", " \n", " Using json.tool from the shell to validate and pretty-print::\n", " \n", " $ echo '{\"json\":\"obj\"}' | python -m json.tool\n", " {\n", " \"json\": \"obj\"\n", " }\n", " $ echo '{ 1.2:3.4}' | python -m json.tool\n", " Expecting property name enclosed in double quotes: line 1 column 3 (char 2)\n", "\n", "PACKAGE CONTENTS\n", " decoder\n", " encoder\n", " scanner\n", " tool\n", "\n", "CLASSES\n", " builtins.ValueError(builtins.Exception)\n", " json.decoder.JSONDecodeError\n", " builtins.object\n", " json.decoder.JSONDecoder\n", " json.encoder.JSONEncoder\n", " \n", " class JSONDecodeError(builtins.ValueError)\n", " | JSONDecodeError(msg, doc, pos)\n", " | \n", " | Subclass of ValueError with the following additional properties:\n", " | \n", " | msg: The unformatted error message\n", " | doc: The JSON document being parsed\n", " | pos: The start index of doc where parsing failed\n", " | lineno: The line corresponding to pos\n", " | colno: The column corresponding to pos\n", " | \n", " | Method resolution order:\n", " | JSONDecodeError\n", " | builtins.ValueError\n", " | builtins.Exception\n", " | builtins.BaseException\n", " | builtins.object\n", " | \n", " | Methods defined here:\n", " | \n", " | __init__(self, msg, doc, pos)\n", " | Initialize self. See help(type(self)) for accurate signature.\n", " | \n", " | __reduce__(self)\n", " | Helper for pickle.\n", " | \n", " | ----------------------------------------------------------------------\n", " | Data descriptors defined here:\n", " | \n", " | __weakref__\n", " | list of weak references to the object (if defined)\n", " | \n", " | ----------------------------------------------------------------------\n", " | Static methods inherited from builtins.ValueError:\n", " | \n", " | __new__(*args, **kwargs) from builtins.type\n", " | Create and return a new object. See help(type) for accurate signature.\n", " | \n", " | ----------------------------------------------------------------------\n", " | Methods inherited from builtins.BaseException:\n", " | \n", " | __delattr__(self, name, /)\n", " | Implement delattr(self, name).\n", " | \n", " | __getattribute__(self, name, /)\n", " | Return getattr(self, name).\n", " | \n", " | __repr__(self, /)\n", " | Return repr(self).\n", " | \n", " | __setattr__(self, name, value, /)\n", " | Implement setattr(self, name, value).\n", " | \n", " | __setstate__(...)\n", " | \n", " | __str__(self, /)\n", " | Return str(self).\n", " | \n", " | with_traceback(...)\n", " | Exception.with_traceback(tb) --\n", " | set self.__traceback__ to tb and return self.\n", " | \n", " | ----------------------------------------------------------------------\n", " | Data descriptors inherited from builtins.BaseException:\n", " | \n", " | __cause__\n", " | exception cause\n", " | \n", " | __context__\n", " | exception context\n", " | \n", " | __dict__\n", " | \n", " | __suppress_context__\n", " | \n", " | __traceback__\n", " | \n", " | args\n", " \n", " class JSONDecoder(builtins.object)\n", " | JSONDecoder(*, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, strict=True, object_pairs_hook=None)\n", " | \n", " | Simple JSON decoder\n", " | \n", " | Performs the following translations in decoding by default:\n", " | \n", " | +---------------+-------------------+\n", " | | JSON | Python |\n", " | +===============+===================+\n", " | | object | dict |\n", " | +---------------+-------------------+\n", " | | array | list |\n", " | +---------------+-------------------+\n", " | | string | str |\n", " | +---------------+-------------------+\n", " | | number (int) | int |\n", " | +---------------+-------------------+\n", " | | number (real) | float |\n", " | +---------------+-------------------+\n", " | | true | True |\n", " | +---------------+-------------------+\n", " | | false | False |\n", " | +---------------+-------------------+\n", " | | null | None |\n", " | +---------------+-------------------+\n", " | \n", " | It also understands ``NaN``, ``Infinity``, and ``-Infinity`` as\n", " | their corresponding ``float`` values, which is outside the JSON spec.\n", " | \n", " | Methods defined here:\n", " | \n", " | __init__(self, *, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, strict=True, object_pairs_hook=None)\n", " | ``object_hook``, if specified, will be called with the result\n", " | of every JSON object decoded and its return value will be used in\n", " | place of the given ``dict``. This can be used to provide custom\n", " | deserializations (e.g. to support JSON-RPC class hinting).\n", " | \n", " | ``object_pairs_hook``, if specified will be called with the result of\n", " | every JSON object decoded with an ordered list of pairs. The return\n", " | value of ``object_pairs_hook`` will be used instead of the ``dict``.\n", " | This feature can be used to implement custom decoders.\n", " | If ``object_hook`` is also defined, the ``object_pairs_hook`` takes\n", " | priority.\n", " | \n", " | ``parse_float``, if specified, will be called with the string\n", " | of every JSON float to be decoded. By default this is equivalent to\n", " | float(num_str). This can be used to use another datatype or parser\n", " | for JSON floats (e.g. decimal.Decimal).\n", " | \n", " | ``parse_int``, if specified, will be called with the string\n", " | of every JSON int to be decoded. By default this is equivalent to\n", " | int(num_str). This can be used to use another datatype or parser\n", " | for JSON integers (e.g. float).\n", " | \n", " | ``parse_constant``, if specified, will be called with one of the\n", " | following strings: -Infinity, Infinity, NaN.\n", " | This can be used to raise an exception if invalid JSON numbers\n", " | are encountered.\n", " | \n", " | If ``strict`` is false (true is the default), then control\n", " | characters will be allowed inside strings. Control characters in\n", " | this context are those with character codes in the 0-31 range,\n", " | including ``'\\t'`` (tab), ``'\\n'``, ``'\\r'`` and ``'\\0'``.\n", " | \n", " | decode(self, s, _w=)\n", " | Return the Python representation of ``s`` (a ``str`` instance\n", " | containing a JSON document).\n", " | \n", " | raw_decode(self, s, idx=0)\n", " | Decode a JSON document from ``s`` (a ``str`` beginning with\n", " | a JSON document) and return a 2-tuple of the Python\n", " | representation and the index in ``s`` where the document ended.\n", " | \n", " | This can be used to decode a JSON document from a string that may\n", " | have extraneous data at the end.\n", " | \n", " | ----------------------------------------------------------------------\n", " | Data descriptors defined here:\n", " | \n", " | __dict__\n", " | dictionary for instance variables (if defined)\n", " | \n", " | __weakref__\n", " | list of weak references to the object (if defined)\n", " \n", " class JSONEncoder(builtins.object)\n", " | JSONEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)\n", " | \n", " | Extensible JSON encoder for Python data structures.\n", " | \n", " | Supports the following objects and types by default:\n", " | \n", " | +-------------------+---------------+\n", " | | Python | JSON |\n", " | +===================+===============+\n", " | | dict | object |\n", " | +-------------------+---------------+\n", " | | list, tuple | array |\n", " | +-------------------+---------------+\n", " | | str | string |\n", " | +-------------------+---------------+\n", " | | int, float | number |\n", " | +-------------------+---------------+\n", " | | True | true |\n", " | +-------------------+---------------+\n", " | | False | false |\n", " | +-------------------+---------------+\n", " | | None | null |\n", " | +-------------------+---------------+\n", " | \n", " | To extend this to recognize other objects, subclass and implement a\n", " | ``.default()`` method with another method that returns a serializable\n", " | object for ``o`` if possible, otherwise it should call the superclass\n", " | implementation (to raise ``TypeError``).\n", " | \n", " | Methods defined here:\n", " | \n", " | __init__(self, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)\n", " | Constructor for JSONEncoder, with sensible defaults.\n", " | \n", " | If skipkeys is false, then it is a TypeError to attempt\n", " | encoding of keys that are not str, int, float or None. If\n", " | skipkeys is True, such items are simply skipped.\n", " | \n", " | If ensure_ascii is true, the output is guaranteed to be str\n", " | objects with all incoming non-ASCII characters escaped. If\n", " | ensure_ascii is false, the output can contain non-ASCII characters.\n", " | \n", " | If check_circular is true, then lists, dicts, and custom encoded\n", " | objects will be checked for circular references during encoding to\n", " | prevent an infinite recursion (which would cause an RecursionError).\n", " | Otherwise, no such check takes place.\n", " | \n", " | If allow_nan is true, then NaN, Infinity, and -Infinity will be\n", " | encoded as such. This behavior is not JSON specification compliant,\n", " | but is consistent with most JavaScript based encoders and decoders.\n", " | Otherwise, it will be a ValueError to encode such floats.\n", " | \n", " | If sort_keys is true, then the output of dictionaries will be\n", " | sorted by key; this is useful for regression tests to ensure\n", " | that JSON serializations can be compared on a day-to-day basis.\n", " | \n", " | If indent is a non-negative integer, then JSON array\n", " | elements and object members will be pretty-printed with that\n", " | indent level. An indent level of 0 will only insert newlines.\n", " | None is the most compact representation.\n", " | \n", " | If specified, separators should be an (item_separator, key_separator)\n", " | tuple. The default is (', ', ': ') if *indent* is ``None`` and\n", " | (',', ': ') otherwise. To get the most compact JSON representation,\n", " | you should specify (',', ':') to eliminate whitespace.\n", " | \n", " | If specified, default is a function that gets called for objects\n", " | that can't otherwise be serialized. It should return a JSON encodable\n", " | version of the object or raise a ``TypeError``.\n", " | \n", " | default(self, o)\n", " | Implement this method in a subclass such that it returns\n", " | a serializable object for ``o``, or calls the base implementation\n", " | (to raise a ``TypeError``).\n", " | \n", " | For example, to support arbitrary iterators, you could\n", " | implement default like this::\n", " | \n", " | def default(self, o):\n", " | try:\n", " | iterable = iter(o)\n", " | except TypeError:\n", " | pass\n", " | else:\n", " | return list(iterable)\n", " | # Let the base class default method raise the TypeError\n", " | return JSONEncoder.default(self, o)\n", " | \n", " | encode(self, o)\n", " | Return a JSON string representation of a Python data structure.\n", " | \n", " | >>> from json.encoder import JSONEncoder\n", " | >>> JSONEncoder().encode({\"foo\": [\"bar\", \"baz\"]})\n", " | '{\"foo\": [\"bar\", \"baz\"]}'\n", " | \n", " | iterencode(self, o, _one_shot=False)\n", " | Encode the given object and yield each string\n", " | representation as available.\n", " | \n", " | For example::\n", " | \n", " | for chunk in JSONEncoder().iterencode(bigobject):\n", " | mysocket.write(chunk)\n", " | \n", " | ----------------------------------------------------------------------\n", " | Data descriptors defined here:\n", " | \n", " | __dict__\n", " | dictionary for instance variables (if defined)\n", " | \n", " | __weakref__\n", " | list of weak references to the object (if defined)\n", " | \n", " | ----------------------------------------------------------------------\n", " | Data and other attributes defined here:\n", " | \n", " | item_separator = ', '\n", " | \n", " | key_separator = ': '\n", "\n", "FUNCTIONS\n", " dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)\n", " Serialize ``obj`` as a JSON formatted stream to ``fp`` (a\n", " ``.write()``-supporting file-like object).\n", " \n", " If ``skipkeys`` is true then ``dict`` keys that are not basic types\n", " (``str``, ``int``, ``float``, ``bool``, ``None``) will be skipped\n", " instead of raising a ``TypeError``.\n", " \n", " If ``ensure_ascii`` is false, then the strings written to ``fp`` can\n", " contain non-ASCII characters if they appear in strings contained in\n", " ``obj``. Otherwise, all such characters are escaped in JSON strings.\n", " \n", " If ``check_circular`` is false, then the circular reference check\n", " for container types will be skipped and a circular reference will\n", " result in an ``RecursionError`` (or worse).\n", " \n", " If ``allow_nan`` is false, then it will be a ``ValueError`` to\n", " serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``)\n", " in strict compliance of the JSON specification, instead of using the\n", " JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).\n", " \n", " If ``indent`` is a non-negative integer, then JSON array elements and\n", " object members will be pretty-printed with that indent level. An indent\n", " level of 0 will only insert newlines. ``None`` is the most compact\n", " representation.\n", " \n", " If specified, ``separators`` should be an ``(item_separator, key_separator)``\n", " tuple. The default is ``(', ', ': ')`` if *indent* is ``None`` and\n", " ``(',', ': ')`` otherwise. To get the most compact JSON representation,\n", " you should specify ``(',', ':')`` to eliminate whitespace.\n", " \n", " ``default(obj)`` is a function that should return a serializable version\n", " of obj or raise TypeError. The default simply raises TypeError.\n", " \n", " If *sort_keys* is true (default: ``False``), then the output of\n", " dictionaries will be sorted by key.\n", " \n", " To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the\n", " ``.default()`` method to serialize additional types), specify it with\n", " the ``cls`` kwarg; otherwise ``JSONEncoder`` is used.\n", " \n", " dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)\n", " Serialize ``obj`` to a JSON formatted ``str``.\n", " \n", " If ``skipkeys`` is true then ``dict`` keys that are not basic types\n", " (``str``, ``int``, ``float``, ``bool``, ``None``) will be skipped\n", " instead of raising a ``TypeError``.\n", " \n", " If ``ensure_ascii`` is false, then the return value can contain non-ASCII\n", " characters if they appear in strings contained in ``obj``. Otherwise, all\n", " such characters are escaped in JSON strings.\n", " \n", " If ``check_circular`` is false, then the circular reference check\n", " for container types will be skipped and a circular reference will\n", " result in an ``RecursionError`` (or worse).\n", " \n", " If ``allow_nan`` is false, then it will be a ``ValueError`` to\n", " serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) in\n", " strict compliance of the JSON specification, instead of using the\n", " JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).\n", " \n", " If ``indent`` is a non-negative integer, then JSON array elements and\n", " object members will be pretty-printed with that indent level. An indent\n", " level of 0 will only insert newlines. ``None`` is the most compact\n", " representation.\n", " \n", " If specified, ``separators`` should be an ``(item_separator, key_separator)``\n", " tuple. The default is ``(', ', ': ')`` if *indent* is ``None`` and\n", " ``(',', ': ')`` otherwise. To get the most compact JSON representation,\n", " you should specify ``(',', ':')`` to eliminate whitespace.\n", " \n", " ``default(obj)`` is a function that should return a serializable version\n", " of obj or raise TypeError. The default simply raises TypeError.\n", " \n", " If *sort_keys* is true (default: ``False``), then the output of\n", " dictionaries will be sorted by key.\n", " \n", " To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the\n", " ``.default()`` method to serialize additional types), specify it with\n", " the ``cls`` kwarg; otherwise ``JSONEncoder`` is used.\n", " \n", " load(fp, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)\n", " Deserialize ``fp`` (a ``.read()``-supporting file-like object containing\n", " a JSON document) to a Python object.\n", " \n", " ``object_hook`` is an optional function that will be called with the\n", " result of any object literal decode (a ``dict``). The return value of\n", " ``object_hook`` will be used instead of the ``dict``. This feature\n", " can be used to implement custom decoders (e.g. JSON-RPC class hinting).\n", " \n", " ``object_pairs_hook`` is an optional function that will be called with the\n", " result of any object literal decoded with an ordered list of pairs. The\n", " return value of ``object_pairs_hook`` will be used instead of the ``dict``.\n", " This feature can be used to implement custom decoders. If ``object_hook``\n", " is also defined, the ``object_pairs_hook`` takes priority.\n", " \n", " To use a custom ``JSONDecoder`` subclass, specify it with the ``cls``\n", " kwarg; otherwise ``JSONDecoder`` is used.\n", " \n", " loads(s, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)\n", " Deserialize ``s`` (a ``str``, ``bytes`` or ``bytearray`` instance\n", " containing a JSON document) to a Python object.\n", " \n", " ``object_hook`` is an optional function that will be called with the\n", " result of any object literal decode (a ``dict``). The return value of\n", " ``object_hook`` will be used instead of the ``dict``. This feature\n", " can be used to implement custom decoders (e.g. JSON-RPC class hinting).\n", " \n", " ``object_pairs_hook`` is an optional function that will be called with the\n", " result of any object literal decoded with an ordered list of pairs. The\n", " return value of ``object_pairs_hook`` will be used instead of the ``dict``.\n", " This feature can be used to implement custom decoders. If ``object_hook``\n", " is also defined, the ``object_pairs_hook`` takes priority.\n", " \n", " ``parse_float``, if specified, will be called with the string\n", " of every JSON float to be decoded. By default this is equivalent to\n", " float(num_str). This can be used to use another datatype or parser\n", " for JSON floats (e.g. decimal.Decimal).\n", " \n", " ``parse_int``, if specified, will be called with the string\n", " of every JSON int to be decoded. By default this is equivalent to\n", " int(num_str). This can be used to use another datatype or parser\n", " for JSON integers (e.g. float).\n", " \n", " ``parse_constant``, if specified, will be called with one of the\n", " following strings: -Infinity, Infinity, NaN.\n", " This can be used to raise an exception if invalid JSON numbers\n", " are encountered.\n", " \n", " To use a custom ``JSONDecoder`` subclass, specify it with the ``cls``\n", " kwarg; otherwise ``JSONDecoder`` is used.\n", "\n", "DATA\n", " __all__ = ['dump', 'dumps', 'load', 'loads', 'JSONDecoder', 'JSONDecod...\n", "\n", "VERSION\n", " 2.0.9\n", "\n", "AUTHOR\n", " Bob Ippolito \n", "\n", "FILE\n", " /usr/lib64/python3.9/json/__init__.py\n", "\n", "\n" ] } ], "source": [ "help(json)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Blahblah" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Object Oriented?" ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [], "source": [ "i = 42" ] }, { "cell_type": "code", "execution_count": 31, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "int" ] }, "execution_count": 31, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(i)" ] }, { "cell_type": "code", "execution_count": 32, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "list" ] }, "execution_count": 32, "metadata": {}, "output_type": "execute_result" } ], "source": [ "l = [1, 'eins', 1.0]\n", "type(l)" ] }, { "cell_type": "code", "execution_count": 33, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "140299267714496" ] }, "execution_count": 33, "metadata": {}, "output_type": "execute_result" } ], "source": [ "id(l)" ] }, { "cell_type": "code", "execution_count": 34, "metadata": {}, "outputs": [], "source": [ "l1 = []" ] }, { "cell_type": "code", "execution_count": 35, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "140299267930496" ] }, "execution_count": 35, "metadata": {}, "output_type": "execute_result" } ], "source": [ "id(l1)" ] }, { "cell_type": "code", "execution_count": 36, "metadata": {}, "outputs": [], "source": [ "l.append('blah')" ] }, { "cell_type": "code", "execution_count": 37, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 'eins', 1.0, 'blah']" ] }, "execution_count": 37, "metadata": {}, "output_type": "execute_result" } ], "source": [ "l" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# MQTT" ] }, { "cell_type": "code", "execution_count": 38, "metadata": {}, "outputs": [], "source": [ "import json" ] }, { "cell_type": "code", "execution_count": 39, "metadata": {}, "outputs": [], "source": [ "schweissparameter_aussi = {\n", " 'strom_ma': 200004,\n", " 'spannung_v': 10000.01,\n", "}" ] }, { "cell_type": "code", "execution_count": 40, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'{\"strom_ma\": 200004, \"spannung_v\": 10000.01}'" ] }, "execution_count": 40, "metadata": {}, "output_type": "execute_result" } ], "source": [ "aufs_kabel = json.dumps(schweissparameter_aussi)\n", "aufs_kabel" ] }, { "cell_type": "code", "execution_count": 41, "metadata": {}, "outputs": [], "source": [ "# aufs_kabel: publish() nach mqtt, topic \"maschine_112\"" ] }, { "cell_type": "code", "execution_count": 42, "metadata": {}, "outputs": [], "source": [ "# vom kabel, subscribe()d an mqtt, topic \"maschine_112\"" ] }, { "cell_type": "code", "execution_count": 43, "metadata": {}, "outputs": [], "source": [ "vom_kabel = aufs_kabel" ] }, { "cell_type": "code", "execution_count": 44, "metadata": {}, "outputs": [], "source": [ "schweissparameter_eini = json.loads(vom_kabel)" ] }, { "cell_type": "code", "execution_count": 45, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'strom_ma': 200004, 'spannung_v': 10000.01}" ] }, "execution_count": 45, "metadata": {}, "output_type": "execute_result" } ], "source": [ "schweissparameter_eini" ] }, { "cell_type": "code", "execution_count": 46, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " 'strom_a'\n" ] } ], "source": [ "try:\n", " schweissparameter_eini['strom_a']\n", "except Exception as e:\n", " print(type(e), e)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Syntax etc." ] }, { "cell_type": "code", "execution_count": 47, "metadata": {}, "outputs": [], "source": [ "a = 43" ] }, { "cell_type": "code", "execution_count": 48, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "fertig\n" ] } ], "source": [ "if a == 42:\n", " print('jaja, eh 42')\n", " print(a)\n", "print('fertig')" ] }, { "cell_type": "code", "execution_count": 49, "metadata": {}, "outputs": [], "source": [ "a = 42; b = 666" ] }, { "cell_type": "code", "execution_count": 50, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "42" ] }, "execution_count": 50, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a" ] }, { "cell_type": "code", "execution_count": 51, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "666" ] }, "execution_count": 51, "metadata": {}, "output_type": "execute_result" } ], "source": [ "b" ] }, { "cell_type": "code", "execution_count": 52, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello World\n" ] } ], "source": [ "print('Hello', 'World')" ] }, { "cell_type": "code", "execution_count": 53, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello World\n" ] } ], "source": [ "print(\n", " \n", " \n", " 'Hello',\n", " \n", " 'World')" ] }, { "cell_type": "code", "execution_count": 54, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello***World\n" ] } ], "source": [ "print('Hello', 'World', sep='***')" ] }, { "cell_type": "code", "execution_count": 55, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'hallo'" ] }, "execution_count": 55, "metadata": {}, "output_type": "execute_result" } ], "source": [ "'hallo'" ] }, { "cell_type": "code", "execution_count": 56, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'hallo'" ] }, "execution_count": 56, "metadata": {}, "output_type": "execute_result" } ], "source": [ "\"hallo\"" ] }, { "cell_type": "code", "execution_count": 57, "metadata": {}, "outputs": [], "source": [ "s = \"hal'lo\"" ] }, { "cell_type": "code", "execution_count": 58, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "\"'\"" ] }, "execution_count": 58, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s[3]" ] }, { "cell_type": "code", "execution_count": 59, "metadata": {}, "outputs": [], "source": [ "s = 'hal\"lo'" ] }, { "cell_type": "code", "execution_count": 60, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'\"'" ] }, "execution_count": 60, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s[3]" ] }, { "cell_type": "code", "execution_count": 61, "metadata": {}, "outputs": [], "source": [ "s = 'ha\"ll\\''" ] }, { "cell_type": "code", "execution_count": 62, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'\"'" ] }, "execution_count": 62, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s[2]" ] }, { "cell_type": "code", "execution_count": 63, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "\"'\"" ] }, "execution_count": 63, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s[5]" ] }, { "cell_type": "code", "execution_count": 64, "metadata": {}, "outputs": [], "source": [ "s = '''das\n", "ist\n", "ein\n", "multiline\n", "string'''" ] }, { "cell_type": "code", "execution_count": 65, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "das\n", "ist\n", "ein\n", "multiline\n", "string\n" ] } ], "source": [ "print(s)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Commandline Arguments" ] }, { "cell_type": "code", "execution_count": 66, "metadata": {}, "outputs": [], "source": [ "import sys" ] }, { "cell_type": "code", "execution_count": 67, "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", " 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": 68, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'linux'" ] }, "execution_count": 68, "metadata": {}, "output_type": "execute_result" } ], "source": [ "sys.platform" ] }, { "cell_type": "code", "execution_count": 69, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'/home/jfasch/venv/jfasch-home/bin/python'" ] }, "execution_count": 69, "metadata": {}, "output_type": "execute_result" } ], "source": [ "sys.executable" ] }, { "cell_type": "code", "execution_count": 70, "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-2c445fb3-6ca4-4628-b9d9-7cfbbff55326.json']" ] }, "execution_count": 70, "metadata": {}, "output_type": "execute_result" } ], "source": [ "sys.argv" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Variables" ] }, { "cell_type": "code", "execution_count": 71, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "int" ] }, "execution_count": 71, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a = 42\n", "type(a)" ] }, { "cell_type": "code", "execution_count": 72, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "float" ] }, "execution_count": 72, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a = 1.5\n", "type(a)" ] }, { "cell_type": "code", "execution_count": 73, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "list" ] }, "execution_count": 73, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a = [1, 'eins']\n", "type(a)" ] }, { "cell_type": "code", "execution_count": 74, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " name 'doesnt_exist' is not defined\n" ] } ], "source": [ "try:\n", " doesnt_exist\n", "except Exception as e:\n", " print(type(e), e)" ] }, { "cell_type": "code", "execution_count": 75, "metadata": {}, "outputs": [], "source": [ "_a = 42" ] }, { "cell_type": "code", "execution_count": 76, "metadata": {}, "outputs": [], "source": [ "_a666 = 666" ] }, { "cell_type": "code", "execution_count": 77, "metadata": {}, "outputs": [], "source": [ "a = 1\n", "b = 2\n", "c = 3" ] }, { "cell_type": "code", "execution_count": 78, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 78, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a" ] }, { "cell_type": "code", "execution_count": 79, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "2" ] }, "execution_count": 79, "metadata": {}, "output_type": "execute_result" } ], "source": [ "b" ] }, { "cell_type": "code", "execution_count": 80, "metadata": {}, "outputs": [], "source": [ "# ..." ] }, { "cell_type": "code", "execution_count": 81, "metadata": {}, "outputs": [], "source": [ "a, b, c = 1, 2, 3" ] }, { "cell_type": "code", "execution_count": 82, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 82, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a" ] }, { "cell_type": "code", "execution_count": 83, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "2" ] }, "execution_count": 83, "metadata": {}, "output_type": "execute_result" } ], "source": [ "b" ] }, { "cell_type": "code", "execution_count": 84, "metadata": {}, "outputs": [], "source": [ "# ..." ] }, { "cell_type": "code", "execution_count": 85, "metadata": {}, "outputs": [], "source": [ "(a, b, c) = (1, 2, 3)" ] }, { "cell_type": "code", "execution_count": 86, "metadata": {}, "outputs": [], "source": [ "a = b = c = 1" ] }, { "cell_type": "code", "execution_count": 87, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(1, 1, 1)" ] }, "execution_count": 87, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a, b, c" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Assignment Details" ] }, { "cell_type": "code", "execution_count": 88, "metadata": {}, "outputs": [], "source": [ "a = 42" ] }, { "cell_type": "code", "execution_count": 89, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "140299402960464" ] }, "execution_count": 89, "metadata": {}, "output_type": "execute_result" } ], "source": [ "id(a)" ] }, { "cell_type": "code", "execution_count": 90, "metadata": {}, "outputs": [], "source": [ "b = a" ] }, { "cell_type": "code", "execution_count": 91, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "42" ] }, "execution_count": 91, "metadata": {}, "output_type": "execute_result" } ], "source": [ "b" ] }, { "cell_type": "code", "execution_count": 92, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "140299402960464" ] }, "execution_count": 92, "metadata": {}, "output_type": "execute_result" } ], "source": [ "id(b)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Datatypes" ] }, { "cell_type": "code", "execution_count": 93, "metadata": {}, "outputs": [], "source": [ "i = 666" ] }, { "cell_type": "code", "execution_count": 94, "metadata": {}, "outputs": [], "source": [ "i = 2**32-1" ] }, { "cell_type": "code", "execution_count": 95, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "4294967295" ] }, "execution_count": 95, "metadata": {}, "output_type": "execute_result" } ], "source": [ "i" ] }, { "cell_type": "code", "execution_count": 96, "metadata": {}, "outputs": [], "source": [ "i = 2**64 - 1" ] }, { "cell_type": "code", "execution_count": 97, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "18446744073709551615" ] }, "execution_count": 97, "metadata": {}, "output_type": "execute_result" } ], "source": [ "i" ] }, { "cell_type": "code", "execution_count": 98, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'0b10000000000000000000000000000000000000000000000000000000000000000'" ] }, "execution_count": 98, "metadata": {}, "output_type": "execute_result" } ], "source": [ "bin(2**64)" ] }, { "cell_type": "code", "execution_count": 99, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "19950631168807583848837421626835850838234968318861924548520089498529438830221946631919961684036194597899331129423209124271556491349413781117593785932096323957855730046793794526765246551266059895520550086918193311542508608460618104685509074866089624888090489894838009253941633257850621568309473902556912388065225096643874441046759871626985453222868538161694315775629640762836880760732228535091641476183956381458969463899410840960536267821064621427333394036525565649530603142680234969400335934316651459297773279665775606172582031407994198179607378245683762280037302885487251900834464581454650557929601414833921615734588139257095379769119277800826957735674444123062018757836325502728323789270710373802866393031428133241401624195671690574061419654342324638801248856147305207431992259611796250130992860241708340807605932320161268492288496255841312844061536738951487114256315111089745514203313820202931640957596464756010405845841566072044962867016515061920631004186422275908670900574606417856951911456055068251250406007519842261898059237118054444788072906395242548339221982707404473162376760846613033778706039803413197133493654622700563169937455508241780972810983291314403571877524768509857276937926433221599399876886660808368837838027643282775172273657572744784112294389733810861607423253291974813120197604178281965697475898164531258434135959862784130128185406283476649088690521047580882615823961985770122407044330583075869039319604603404973156583208672105913300903752823415539745394397715257455290510212310947321610753474825740775273986348298498340756937955646638621874569499279016572103701364433135817214311791398222983845847334440270964182851005072927748364550578634501100852987812389473928699540834346158807043959118985815145779177143619698728131459483783202081474982171858011389071228250905826817436220577475921417653715687725614904582904992461028630081535583308130101987675856234343538955409175623400844887526162643568648833519463720377293240094456246923254350400678027273837755376406726898636241037491410966718557050759098100246789880178271925953381282421954028302759408448955014676668389697996886241636313376393903373455801407636741877711055384225739499110186468219696581651485130494222369947714763069155468217682876200362777257723781365331611196811280792669481887201298643660768551639860534602297871557517947385246369446923087894265948217008051120322365496288169035739121368338393591756418733850510970271613915439590991598154654417336311656936031122249937969999226781732358023111862644575299135758175008199839236284615249881088960232244362173771618086357015468484058622329792853875623486556440536962622018963571028812361567512543338303270029097668650568557157505516727518899194129711337690149916181315171544007728650573189557450920330185304847113818315407324053319038462084036421763703911550639789000742853672196280903477974533320468368795868580237952218629120080742819551317948157624448298518461509704888027274721574688131594750409732115080498190455803416826949787141316063210686391511681774304792596709376" ] }, "execution_count": 99, "metadata": {}, "output_type": "execute_result" } ], "source": [ "2**10000" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Floor division**" ] }, { "cell_type": "code", "execution_count": 100, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1.5" ] }, "execution_count": 100, "metadata": {}, "output_type": "execute_result" } ], "source": [ "3/2 # == 1 in Python 2" ] }, { "cell_type": "code", "execution_count": 101, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 101, "metadata": {}, "output_type": "execute_result" } ], "source": [ "3//2" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Modulo**: Rest bei Division" ] }, { "cell_type": "code", "execution_count": 102, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 102, "metadata": {}, "output_type": "execute_result" } ], "source": [ "7%3" ] }, { "cell_type": "code", "execution_count": 103, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "2" ] }, "execution_count": 103, "metadata": {}, "output_type": "execute_result" } ], "source": [ "8%3" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Precedence rules**" ] }, { "cell_type": "code", "execution_count": 104, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "7" ] }, "execution_count": 104, "metadata": {}, "output_type": "execute_result" } ], "source": [ "1 + 2 * 3" ] }, { "cell_type": "code", "execution_count": 105, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "9" ] }, "execution_count": 105, "metadata": {}, "output_type": "execute_result" } ], "source": [ "(1 + 2) * 3" ] }, { "cell_type": "code", "execution_count": 106, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "2" ] }, "execution_count": 106, "metadata": {}, "output_type": "execute_result" } ], "source": [ "3 * 4 % 5" ] }, { "cell_type": "code", "execution_count": 107, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "2" ] }, "execution_count": 107, "metadata": {}, "output_type": "execute_result" } ], "source": [ "(3 * 4) % 5" ] }, { "cell_type": "code", "execution_count": 108, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "12" ] }, "execution_count": 108, "metadata": {}, "output_type": "execute_result" } ], "source": [ "3 * (4 % 5)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Datatype Conversions" ] }, { "cell_type": "code", "execution_count": 109, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "int" ] }, "execution_count": 109, "metadata": {}, "output_type": "execute_result" } ], "source": [ "i = 42\n", "type(i)" ] }, { "cell_type": "code", "execution_count": 110, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "str" ] }, "execution_count": 110, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s = '42'\n", "type(s)" ] }, { "cell_type": "code", "execution_count": 111, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 111, "metadata": {}, "output_type": "execute_result" } ], "source": [ "i == s" ] }, { "cell_type": "code", "execution_count": 112, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'42'" ] }, "execution_count": 112, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Explicit Conversion:" ] }, { "cell_type": "code", "execution_count": 113, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "42" ] }, "execution_count": 113, "metadata": {}, "output_type": "execute_result" } ], "source": [ "int(s)" ] }, { "cell_type": "code", "execution_count": 114, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'666'" ] }, "execution_count": 114, "metadata": {}, "output_type": "execute_result" } ], "source": [ "str(666)" ] }, { "cell_type": "code", "execution_count": 115, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'[1, 2]'" ] }, "execution_count": 115, "metadata": {}, "output_type": "execute_result" } ], "source": [ "str([1,2])" ] }, { "cell_type": "code", "execution_count": 116, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " invalid literal for int() with base 10: '0xdeadbeef'\n" ] } ], "source": [ "try:\n", " int('0xdeadbeef')\n", "except Exception as e:\n", " print(type(e), e)" ] }, { "cell_type": "code", "execution_count": 117, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "3735928559" ] }, "execution_count": 117, "metadata": {}, "output_type": "execute_result" } ], "source": [ "int('0xdeadbeef', 16)" ] }, { "cell_type": "code", "execution_count": 118, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1.234" ] }, "execution_count": 118, "metadata": {}, "output_type": "execute_result" } ], "source": [ "float('1.234')" ] }, { "cell_type": "code", "execution_count": 119, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " could not convert string to float: '1,234'\n" ] } ], "source": [ "try:\n", " float('1,234')\n", "except Exception as e:\n", " print(type(e), e)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Object Lifetime" ] }, { "cell_type": "code", "execution_count": 120, "metadata": {}, "outputs": [], "source": [ "l1 = [1,2,3]" ] }, { "cell_type": "code", "execution_count": 121, "metadata": {}, "outputs": [], "source": [ "l2 = l1" ] }, { "cell_type": "code", "execution_count": 122, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "140299327492352" ] }, "execution_count": 122, "metadata": {}, "output_type": "execute_result" } ], "source": [ "id(l1)" ] }, { "cell_type": "code", "execution_count": 123, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "140299327492352" ] }, "execution_count": 123, "metadata": {}, "output_type": "execute_result" } ], "source": [ "id(l2)" ] }, { "cell_type": "code", "execution_count": 124, "metadata": {}, "outputs": [], "source": [ "del l1" ] }, { "cell_type": "code", "execution_count": 125, "metadata": {}, "outputs": [], "source": [ "del l2" ] }, { "cell_type": "code", "execution_count": 126, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1, 2, 3]\n" ] } ], "source": [ "l1 = [1,2,3]\n", "def f(l2):\n", " print(l2)\n", "f(l1)" ] }, { "cell_type": "code", "execution_count": 127, "metadata": {}, "outputs": [], "source": [ "del l1" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Boolean, Short Circuit Evaluation" ] }, { "cell_type": "code", "execution_count": 128, "metadata": {}, "outputs": [], "source": [ "def func_false():\n", " print('func_false called')\n", " return False\n", "def func_true():\n", " print('func_true called')\n", " return True" ] }, { "cell_type": "code", "execution_count": 129, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "func_true called\n", "func_false called\n" ] }, { "data": { "text/plain": [ "False" ] }, "execution_count": 129, "metadata": {}, "output_type": "execute_result" } ], "source": [ "func_true() and func_false()" ] }, { "cell_type": "code", "execution_count": 130, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "func_true called\n", "func_true called\n" ] }, { "data": { "text/plain": [ "True" ] }, "execution_count": 130, "metadata": {}, "output_type": "execute_result" } ], "source": [ "func_true() and func_true()" ] }, { "cell_type": "code", "execution_count": 131, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "func_false called\n" ] }, { "data": { "text/plain": [ "False" ] }, "execution_count": 131, "metadata": {}, "output_type": "execute_result" } ], "source": [ "func_false() and func_true()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# More String Methods" ] }, { "cell_type": "code", "execution_count": 132, "metadata": {}, "outputs": [], "source": [ "s1 = 'abc'\n", "s2 = 'def'" ] }, { "cell_type": "code", "execution_count": 133, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'abcdef'" ] }, "execution_count": 133, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s1 + s2" ] }, { "cell_type": "code", "execution_count": 134, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'abc hallo'" ] }, "execution_count": 134, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s1 += ' hallo'\n", "s1" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Dictionary Preview" ] }, { "cell_type": "code", "execution_count": 135, "metadata": {}, "outputs": [], "source": [ "d = {\n", " 'm': 'Mr.',\n", " 'f': 'Mrs.',\n", " 'd': 'Prs.',\n", "}" ] }, { "cell_type": "code", "execution_count": 136, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 136, "metadata": {}, "output_type": "execute_result" } ], "source": [ "'m' in d" ] }, { "cell_type": "code", "execution_count": 137, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 137, "metadata": {}, "output_type": "execute_result" } ], "source": [ "'x' in d" ] }, { "cell_type": "code", "execution_count": 138, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 138, "metadata": {}, "output_type": "execute_result" } ], "source": [ "'x' not in d" ] }, { "cell_type": "code", "execution_count": 139, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Mr.'" ] }, "execution_count": 139, "metadata": {}, "output_type": "execute_result" } ], "source": [ "d['m']" ] }, { "cell_type": "code", "execution_count": 140, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " 'x'\n" ] } ], "source": [ "try:\n", " d['x']\n", "except Exception as e:\n", " print(type(e), e)" ] }, { "cell_type": "code", "execution_count": 141, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'m': 'Mr.', 'f': 'Mrs.', 'd': 'Prs.'}" ] }, "execution_count": 141, "metadata": {}, "output_type": "execute_result" } ], "source": [ "d" ] }, { "cell_type": "code", "execution_count": 142, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "m\n", "f\n", "d\n" ] } ], "source": [ "for element in d:\n", " print(element)" ] }, { "cell_type": "code", "execution_count": 143, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "m\n", "f\n", "d\n" ] } ], "source": [ "for key in d.keys():\n", " print(key)" ] }, { "cell_type": "code", "execution_count": 144, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Mr.\n", "Mrs.\n", "Prs.\n" ] } ], "source": [ "for value in d.values():\n", " print(value)" ] }, { "cell_type": "code", "execution_count": 145, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "('m', 'Mr.')\n", "('f', 'Mrs.')\n", "('d', 'Prs.')\n" ] } ], "source": [ "for element in d.items():\n", " print(element)" ] }, { "cell_type": "code", "execution_count": 146, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "m Mr.\n", "f Mrs.\n", "d Prs.\n" ] } ], "source": [ "for element in d.items():\n", " key = element[0]\n", " value = element[1]\n", " print(key, value)" ] }, { "cell_type": "code", "execution_count": 147, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "m Mr.\n", "f Mrs.\n", "d Prs.\n" ] } ], "source": [ "for key, value in d.items():\n", " print(key, value)" ] }, { "cell_type": "code", "execution_count": 148, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1\n", "2\n", "3\n" ] } ], "source": [ "for element in [1,2,3]:\n", " print(element)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# More String Methods" ] }, { "cell_type": "code", "execution_count": 149, "metadata": {}, "outputs": [], "source": [ "s = 'abc:1:2:def'" ] }, { "cell_type": "code", "execution_count": 150, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['abc', '1', '2', 'def']" ] }, "execution_count": 150, "metadata": {}, "output_type": "execute_result" } ], "source": [ "fields = s.split(':')\n", "fields" ] }, { "cell_type": "code", "execution_count": 151, "metadata": {}, "outputs": [], "source": [ "name, uid, gid, home = fields # <--- tuple unpacking" ] }, { "cell_type": "code", "execution_count": 152, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "name: abc , uid: 1 , gid: 2 , home: def\n" ] } ], "source": [ "print('name:', name, ', uid:', uid, ', gid:', gid, ', home:', home)" ] }, { "cell_type": "code", "execution_count": 153, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "name: abc, uid: 1, gid: 2, home: def\n" ] } ], "source": [ "print(f'name: {name}, uid: {uid}, gid: {gid}, home: {home}')" ] }, { "cell_type": "code", "execution_count": 154, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'m,f,d'" ] }, "execution_count": 154, "metadata": {}, "output_type": "execute_result" } ], "source": [ "sex_options = ['m', 'f', 'd']\n", "','.join(sex_options)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Compound Datatypes" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## ``list``: Mutable" ] }, { "cell_type": "code", "execution_count": 155, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "list" ] }, "execution_count": 155, "metadata": {}, "output_type": "execute_result" } ], "source": [ "l = [1,2,'drei']\n", "type(l)" ] }, { "cell_type": "code", "execution_count": 156, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "140298898107648" ] }, "execution_count": 156, "metadata": {}, "output_type": "execute_result" } ], "source": [ "id(l)" ] }, { "cell_type": "code", "execution_count": 157, "metadata": {}, "outputs": [], "source": [ "l.append(4)" ] }, { "cell_type": "code", "execution_count": 158, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 2, 'drei', 4]" ] }, "execution_count": 158, "metadata": {}, "output_type": "execute_result" } ], "source": [ "l" ] }, { "cell_type": "code", "execution_count": 159, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "140298898107648" ] }, "execution_count": 159, "metadata": {}, "output_type": "execute_result" } ], "source": [ "id(l)" ] }, { "cell_type": "code", "execution_count": 160, "metadata": {}, "outputs": [], "source": [ "l.extend([5,'sechs',7.0])" ] }, { "cell_type": "code", "execution_count": 161, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 2, 'drei', 4, 5, 'sechs', 7.0]" ] }, "execution_count": 161, "metadata": {}, "output_type": "execute_result" } ], "source": [ "l" ] }, { "cell_type": "code", "execution_count": 162, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "140298898107648" ] }, "execution_count": 162, "metadata": {}, "output_type": "execute_result" } ], "source": [ "id(l)" ] }, { "cell_type": "code", "execution_count": 163, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 2, 'drei', 4, 5, 'sechs', 7.0, 'acht', 9]" ] }, "execution_count": 163, "metadata": {}, "output_type": "execute_result" } ], "source": [ "l += ['acht', 9]\n", "l" ] }, { "cell_type": "code", "execution_count": 164, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 2, 'drei', 4, 5, 'sechs', 7.0, 'acht', 9, 10, 11]" ] }, "execution_count": 164, "metadata": {}, "output_type": "execute_result" } ], "source": [ "l1 = [10, 11]\n", "new_l = l + l1\n", "new_l" ] }, { "cell_type": "code", "execution_count": 165, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 2, 'drei', 4, 5, 'sechs', 7.0, 'acht', 9]" ] }, "execution_count": 165, "metadata": {}, "output_type": "execute_result" } ], "source": [ "l" ] }, { "cell_type": "code", "execution_count": 166, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[10, 11]" ] }, "execution_count": 166, "metadata": {}, "output_type": "execute_result" } ], "source": [ "l1" ] }, { "cell_type": "code", "execution_count": 167, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1,\n", " 2,\n", " 'drei',\n", " 4,\n", " 5,\n", " 'sechs',\n", " 7.0,\n", " 'acht',\n", " 9,\n", " 1,\n", " 2,\n", " 'drei',\n", " 4,\n", " 5,\n", " 'sechs',\n", " 7.0,\n", " 'acht',\n", " 9,\n", " 1,\n", " 2,\n", " 'drei',\n", " 4,\n", " 5,\n", " 'sechs',\n", " 7.0,\n", " 'acht',\n", " 9]" ] }, "execution_count": 167, "metadata": {}, "output_type": "execute_result" } ], "source": [ "l * 3" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### ``list()``: explicit constructor" ] }, { "cell_type": "code", "execution_count": 168, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['a', 'b', 'c']" ] }, "execution_count": 168, "metadata": {}, "output_type": "execute_result" } ], "source": [ "l = ['a', 'b', 'c']\n", "l" ] }, { "cell_type": "code", "execution_count": 169, "metadata": {}, "outputs": [], "source": [ "s = 'abc'" ] }, { "cell_type": "code", "execution_count": 170, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['a', 'b', 'c']" ] }, "execution_count": 170, "metadata": {}, "output_type": "execute_result" } ], "source": [ "l = []\n", "for element in s:\n", " l.append(element)\n", "l" ] }, { "cell_type": "code", "execution_count": 171, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['a', 'b', 'c']" ] }, "execution_count": 171, "metadata": {}, "output_type": "execute_result" } ], "source": [ "l = list(s)\n", "l" ] }, { "cell_type": "code", "execution_count": 172, "metadata": {}, "outputs": [], "source": [ "d = {\n", " 'm': 'Mr.',\n", " 'f': 'Mrs.',\n", " 'd': 'Prs.',\n", "}" ] }, { "cell_type": "code", "execution_count": 173, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['m', 'f', 'd']" ] }, "execution_count": 173, "metadata": {}, "output_type": "execute_result" } ], "source": [ "l = list(d)\n", "l" ] }, { "cell_type": "code", "execution_count": 174, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[0,\n", " 1,\n", " 2,\n", " 3,\n", " 4,\n", " 5,\n", " 6,\n", " 7,\n", " 8,\n", " 9,\n", " 10,\n", " 11,\n", " 12,\n", " 13,\n", " 14,\n", " 15,\n", " 16,\n", " 17,\n", " 18,\n", " 19,\n", " 20,\n", " 21,\n", " 22,\n", " 23]" ] }, "execution_count": 174, "metadata": {}, "output_type": "execute_result" } ], "source": [ "l = list(range(24))\n", "l" ] }, { "cell_type": "code", "execution_count": 175, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 175, "metadata": {}, "output_type": "execute_result" } ], "source": [ "23 in l" ] }, { "cell_type": "code", "execution_count": 176, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 176, "metadata": {}, "output_type": "execute_result" } ], "source": [ "10**100 in l" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## ``tuple``: Immutable" ] }, { "cell_type": "code", "execution_count": 177, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "tuple" ] }, "execution_count": 177, "metadata": {}, "output_type": "execute_result" } ], "source": [ "t = (1,2,'drei')\n", "type(t)" ] }, { "cell_type": "code", "execution_count": 178, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " 'tuple' object has no attribute 'append'\n" ] } ], "source": [ "try:\n", " t.append(4)\n", "except Exception as e:\n", " print(type(e), e)" ] }, { "cell_type": "code", "execution_count": 179, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1\n" ] } ], "source": [ "t_mit_einem_element = (1) # <--- operator precedence\n", "print(t_mit_einem_element)" ] }, { "cell_type": "code", "execution_count": 180, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "eh\n" ] } ], "source": [ "if (True):\n", " print('eh')" ] }, { "cell_type": "code", "execution_count": 181, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "int" ] }, "execution_count": 181, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(t_mit_einem_element)" ] }, { "cell_type": "code", "execution_count": 182, "metadata": { "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "(1,)\n" ] } ], "source": [ "t_mit_einem_element = (1,)\n", "print(t_mit_einem_element)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## ``dict``: Mutable" ] }, { "cell_type": "code", "execution_count": 183, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "dict" ] }, "execution_count": 183, "metadata": {}, "output_type": "execute_result" } ], "source": [ "d = {1:'one', 2:'two'}\n", "type(d)" ] }, { "cell_type": "code", "execution_count": 184, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'one'" ] }, "execution_count": 184, "metadata": {}, "output_type": "execute_result" } ], "source": [ "d[1]" ] }, { "cell_type": "code", "execution_count": 185, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 185, "metadata": {}, "output_type": "execute_result" } ], "source": [ "1 in d" ] }, { "cell_type": "code", "execution_count": 186, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 186, "metadata": {}, "output_type": "execute_result" } ], "source": [ "3 in d" ] }, { "cell_type": "code", "execution_count": 187, "metadata": { "scrolled": true }, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 187, "metadata": {}, "output_type": "execute_result" } ], "source": [ "3 not in d" ] }, { "cell_type": "code", "execution_count": 188, "metadata": {}, "outputs": [], "source": [ "d[3] = 'three'" ] }, { "cell_type": "code", "execution_count": 189, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 189, "metadata": {}, "output_type": "execute_result" } ], "source": [ "3 in d" ] }, { "cell_type": "code", "execution_count": 190, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'three'" ] }, "execution_count": 190, "metadata": {}, "output_type": "execute_result" } ], "source": [ "d[3]" ] }, { "cell_type": "code", "execution_count": 191, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " 4\n" ] } ], "source": [ "try:\n", " d[4]\n", "except Exception as e:\n", " print(type(e), e)" ] }, { "cell_type": "code", "execution_count": 192, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "leider nicht\n" ] } ], "source": [ "value = d.get(4)\n", "if value is None:\n", " print('leider nicht')\n", "else:\n", " print('supi:', value)" ] }, { "cell_type": "code", "execution_count": 193, "metadata": {}, "outputs": [], "source": [ "del d[3]" ] }, { "cell_type": "code", "execution_count": 194, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 194, "metadata": {}, "output_type": "execute_result" } ], "source": [ "3 in d" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## ``set``: Mutable" ] }, { "cell_type": "code", "execution_count": 195, "metadata": {}, "outputs": [], "source": [ "s = {1, 'zwei', 3.0}" ] }, { "cell_type": "code", "execution_count": 196, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 196, "metadata": {}, "output_type": "execute_result" } ], "source": [ "1 in s" ] }, { "cell_type": "code", "execution_count": 197, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 197, "metadata": {}, "output_type": "execute_result" } ], "source": [ "'drei' not in s" ] }, { "cell_type": "code", "execution_count": 198, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 198, "metadata": {}, "output_type": "execute_result" } ], "source": [ "'drei' in s" ] }, { "cell_type": "code", "execution_count": 199, "metadata": {}, "outputs": [], "source": [ "s.add(100)" ] }, { "cell_type": "code", "execution_count": 200, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 200, "metadata": {}, "output_type": "execute_result" } ], "source": [ "100 in s" ] }, { "cell_type": "code", "execution_count": 201, "metadata": {}, "outputs": [], "source": [ "s.remove(1)" ] }, { "cell_type": "code", "execution_count": 202, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 202, "metadata": {}, "output_type": "execute_result" } ], "source": [ "1 in s" ] }, { "cell_type": "code", "execution_count": 203, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " 300\n" ] } ], "source": [ "try:\n", " s.remove(300)\n", "except Exception as e:\n", " print(type(e), e)" ] }, { "cell_type": "code", "execution_count": 204, "metadata": {}, "outputs": [], "source": [ "s1 = {1, 2, 3, 4, 5}\n", "s2 = {4, 5, 6, 7}" ] }, { "cell_type": "code", "execution_count": 205, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{1, 2, 3, 4, 5, 6, 7}" ] }, "execution_count": 205, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s1 | s2" ] }, { "cell_type": "code", "execution_count": 206, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{1, 2, 3}" ] }, "execution_count": 206, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s1 - s2" ] }, { "cell_type": "code", "execution_count": 207, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{1, 2, 3, 6, 7}" ] }, "execution_count": 207, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s1 ^ s2" ] }, { "cell_type": "code", "execution_count": 208, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "3.0\n", "100\n", "zwei\n" ] } ], "source": [ "for element in s:\n", " print(element)" ] }, { "cell_type": "code", "execution_count": 209, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "3.0\n", "100\n", "zwei\n" ] } ], "source": [ "for element in s:\n", " print(element)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Slicing" ] }, { "cell_type": "code", "execution_count": 210, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[45, 1]" ] }, "execution_count": 210, "metadata": {}, "output_type": "execute_result" } ], "source": [ "l = [23, 45, 1, 8]\n", "l[1:3]" ] }, { "cell_type": "code", "execution_count": 211, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[45, 1, 8]" ] }, "execution_count": 211, "metadata": {}, "output_type": "execute_result" } ], "source": [ "l[1:4]" ] }, { "cell_type": "code", "execution_count": 212, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[45, 1, 8]" ] }, "execution_count": 212, "metadata": {}, "output_type": "execute_result" } ], "source": [ "l[1:]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Comprehensions" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## List comprehension" ] }, { "cell_type": "code", "execution_count": 213, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[9, 36, 1, 4]" ] }, "execution_count": 213, "metadata": {}, "output_type": "execute_result" } ], "source": [ "l = [3, 6, 1, 2]\n", "squares = []\n", "for element in l:\n", " squares.append(element**2)\n", "squares" ] }, { "cell_type": "code", "execution_count": 214, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[9, 36, 1, 4]" ] }, "execution_count": 214, "metadata": {}, "output_type": "execute_result" } ], "source": [ "def squares(nums):\n", " squares = []\n", " for element in nums:\n", " squares.append(element**2)\n", " return squares\n", "squares(l)" ] }, { "cell_type": "code", "execution_count": 215, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[3, 6, 1, 2]" ] }, "execution_count": 215, "metadata": {}, "output_type": "execute_result" } ], "source": [ "l" ] }, { "cell_type": "code", "execution_count": 216, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[9, 36, 1, 4]" ] }, "execution_count": 216, "metadata": {}, "output_type": "execute_result" } ], "source": [ "[element**2 for element in l]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## DIctionary Comprehension" ] }, { "cell_type": "code", "execution_count": 217, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[3, 6, 1, 2]" ] }, "execution_count": 217, "metadata": {}, "output_type": "execute_result" } ], "source": [ "l" ] }, { "cell_type": "code", "execution_count": 218, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{3: 9, 6: 36, 1: 1, 2: 4}" ] }, "execution_count": 218, "metadata": {}, "output_type": "execute_result" } ], "source": [ "squares_map = {}\n", "for element in l:\n", " squares_map[element] = element**2\n", "squares_map" ] }, { "cell_type": "code", "execution_count": 219, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{3: 9, 6: 36, 1: 1, 2: 4}" ] }, "execution_count": 219, "metadata": {}, "output_type": "execute_result" } ], "source": [ "{element: element**2 for element in l}" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Set Comprehension" ] }, { "cell_type": "code", "execution_count": 220, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{1, 4, 9, 36}" ] }, "execution_count": 220, "metadata": {}, "output_type": "execute_result" } ], "source": [ "squares_set = set()\n", "for element in l:\n", " squares_set.add(element**2)\n", "squares_set" ] }, { "cell_type": "code", "execution_count": 221, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{1, 4, 9, 36}" ] }, "execution_count": 221, "metadata": {}, "output_type": "execute_result" } ], "source": [ "{element**2 for element in l}" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# ``max``" ] }, { "cell_type": "code", "execution_count": 222, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "5" ] }, "execution_count": 222, "metadata": {}, "output_type": "execute_result" } ], "source": [ "max([2,3,1,5,3])" ] }, { "cell_type": "code", "execution_count": 223, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "5" ] }, "execution_count": 223, "metadata": {}, "output_type": "execute_result" } ], "source": [ "max(2,3,1,5,3)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Generators" ] }, { "cell_type": "code", "execution_count": 224, "metadata": {}, "outputs": [], "source": [ "r = range(3)" ] }, { "cell_type": "code", "execution_count": 225, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0\n", "1\n", "2\n" ] } ], "source": [ "for element in r:\n", " print(element)" ] }, { "cell_type": "code", "execution_count": 226, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "range" ] }, "execution_count": 226, "metadata": {}, "output_type": "execute_result" } ], "source": [ "r = range(3)\n", "type(r)" ] }, { "cell_type": "code", "execution_count": 227, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "range_iterator" ] }, "execution_count": 227, "metadata": {}, "output_type": "execute_result" } ], "source": [ "it = iter(r)\n", "type(it)" ] }, { "cell_type": "code", "execution_count": 228, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0" ] }, "execution_count": 228, "metadata": {}, "output_type": "execute_result" } ], "source": [ "next(it)" ] }, { "cell_type": "code", "execution_count": 229, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 229, "metadata": {}, "output_type": "execute_result" } ], "source": [ "next(it)" ] }, { "cell_type": "code", "execution_count": 230, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "2" ] }, "execution_count": 230, "metadata": {}, "output_type": "execute_result" } ], "source": [ "next(it)" ] }, { "cell_type": "code", "execution_count": 231, "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": "markdown", "metadata": {}, "source": [ "# ``while``" ] }, { "cell_type": "code", "execution_count": 232, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "5050\n" ] } ], "source": [ "summe = 0\n", "num = 1\n", "while num <= 100:\n", " summe += num\n", " num += 1\n", "print(summe)" ] }, { "cell_type": "code", "execution_count": 233, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "5050\n" ] } ], "source": [ "summe = 0\n", "for num in range(1, 101):\n", " summe += num\n", "print(summe)" ] }, { "cell_type": "code", "execution_count": 234, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "5050" ] }, "execution_count": 234, "metadata": {}, "output_type": "execute_result" } ], "source": [ "sum(range(1,101))" ] }, { "cell_type": "code", "execution_count": 235, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "win\n" ] } ], "source": [ "import random\n", "\n", "numtries = 0\n", "won = False\n", "while numtries < 6:\n", " numtries += 1\n", " eyes = random.randrange(1, 7)\n", " if eyes == 6:\n", " won = True\n", " break\n", "if won:\n", " print('win')\n", "else:\n", " print('lose')" ] }, { "cell_type": "code", "execution_count": 236, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "lose\n" ] } ], "source": [ "import random\n", "\n", "numtries = 0\n", "while numtries < 6:\n", " numtries += 1\n", " eyes = random.randrange(1, 7)\n", " if eyes == 6:\n", " print('win')\n", " break\n", "else:\n", " print('lose')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# ``for``, ``enumerate()``" ] }, { "cell_type": "code", "execution_count": 237, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hallo\n", "Joerg\n" ] } ], "source": [ "l = ['Hallo', 'Joerg']\n", "for element in l:\n", " print(element)" ] }, { "cell_type": "code", "execution_count": 238, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hallo\n", "Joerg\n" ] }, { "data": { "text/plain": [ "[None, None]" ] }, "execution_count": 238, "metadata": {}, "output_type": "execute_result" } ], "source": [ "l = ['Hallo', 'Joerg']\n", "[print(element) for element in l]" ] }, { "cell_type": "code", "execution_count": 239, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0 Hallo\n", "1 Joerg\n" ] } ], "source": [ "l = ['Hallo', 'Joerg']\n", "pos = 0\n", "for element in l:\n", " print(pos, element)\n", " pos += 1" ] }, { "cell_type": "code", "execution_count": 240, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "(0, 'Hallo')\n", "(1, 'Joerg')\n" ] } ], "source": [ "l = ['Hallo', 'Joerg']\n", "for element in enumerate(l):\n", " print(element)" ] }, { "cell_type": "code", "execution_count": 241, "metadata": { "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0 Hallo\n", "1 Joerg\n" ] } ], "source": [ "l = ['Hallo', 'Joerg']\n", "for pos, element in enumerate(l):\n", " print(pos, element)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Functions" ] }, { "cell_type": "code", "execution_count": 246, "metadata": {}, "outputs": [], "source": [ "def maximum(a, b):\n", " '''berechnet blah kompliziert blah maximum'''\n", " if a < b:\n", " return b\n", " else:\n", " return a" ] }, { "cell_type": "code", "execution_count": 247, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "function" ] }, "execution_count": 247, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(maximum)" ] }, { "cell_type": "code", "execution_count": 249, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'berechnet blah kompliziert blah maximum'" ] }, "execution_count": 249, "metadata": {}, "output_type": "execute_result" } ], "source": [ "maximum.__doc__" ] }, { "cell_type": "code", "execution_count": 250, "metadata": {}, "outputs": [], "source": [ "a = maximum" ] }, { "cell_type": "code", "execution_count": 251, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "3" ] }, "execution_count": 251, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a(2, 3)" ] }, { "cell_type": "code", "execution_count": 253, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'def'" ] }, "execution_count": 253, "metadata": {}, "output_type": "execute_result" } ], "source": [ "maximum('abc', 'def')" ] }, { "cell_type": "code", "execution_count": 255, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " '<' not supported between instances of 'str' and 'int'\n" ] } ], "source": [ "try:\n", " maximum('1', 1)\n", "except Exception as e:\n", " print(type(e), e)" ] }, { "cell_type": "code", "execution_count": 256, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1.5" ] }, "execution_count": 256, "metadata": {}, "output_type": "execute_result" } ], "source": [ "maximum(1, 1.5)" ] }, { "cell_type": "code", "execution_count": 257, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 257, "metadata": {}, "output_type": "execute_result" } ], "source": [ "1 < 1.5" ] }, { "cell_type": "code", "execution_count": 263, "metadata": {}, "outputs": [], "source": [ "def greet(who, phrase='Guten Morgen'):\n", " print(phrase, who)" ] }, { "cell_type": "code", "execution_count": 265, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Guten Morgen Joerg\n" ] } ], "source": [ "greet('Joerg')" ] }, { "cell_type": "code", "execution_count": 269, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Guten Morgen Joerg\n" ] } ], "source": [ "greet('Joerg', phrase='Guten Morgen')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Iteratoren, Generatoren" ] }, { "cell_type": "code", "execution_count": 270, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "range" ] }, "execution_count": 270, "metadata": {}, "output_type": "execute_result" } ], "source": [ "r = range(3)\n", "type(r)" ] }, { "cell_type": "code", "execution_count": 271, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "range_iterator" ] }, "execution_count": 271, "metadata": {}, "output_type": "execute_result" } ], "source": [ "it = iter(r)\n", "type(it)" ] }, { "cell_type": "code", "execution_count": 272, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0" ] }, "execution_count": 272, "metadata": {}, "output_type": "execute_result" } ], "source": [ "next(it)" ] }, { "cell_type": "code", "execution_count": 274, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 274, "metadata": {}, "output_type": "execute_result" } ], "source": [ "next(it)" ] }, { "cell_type": "code", "execution_count": 275, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "2" ] }, "execution_count": 275, "metadata": {}, "output_type": "execute_result" } ], "source": [ "next(it)" ] }, { "cell_type": "code", "execution_count": 277, "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": 278, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "3" ] }, "execution_count": 278, "metadata": {}, "output_type": "execute_result" } ], "source": [ "l = [3, 4]\n", "it = iter(l)\n", "next(it)" ] }, { "cell_type": "code", "execution_count": 279, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "4" ] }, "execution_count": 279, "metadata": {}, "output_type": "execute_result" } ], "source": [ "next(it)" ] }, { "cell_type": "code", "execution_count": 281, "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": 283, "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": "code", "execution_count": 284, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "3\n", "4\n" ] } ], "source": [ "for element in l:\n", " print(element)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Generatoren" ] }, { "cell_type": "code", "execution_count": 287, "metadata": {}, "outputs": [], "source": [ "def even_numbers(limit):\n", " numbers = []\n", " i = 0\n", " while i < limit:\n", " if i % 2 == 0:\n", " numbers.append(i)\n", " i += 1\n", " return numbers" ] }, { "cell_type": "code", "execution_count": 288, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0\n", "2\n", "4\n", "6\n", "8\n" ] } ], "source": [ "for element in even_numbers(10):\n", " print(element)" ] }, { "cell_type": "code", "execution_count": 289, "metadata": {}, "outputs": [], "source": [ "def even_numbers(limit):\n", " i = 0\n", " while i < limit:\n", " if i % 2 == 0:\n", " yield i\n", " i += 1" ] }, { "cell_type": "code", "execution_count": 290, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "generator" ] }, "execution_count": 290, "metadata": {}, "output_type": "execute_result" } ], "source": [ "en = even_numbers(10)\n", "type(en)" ] }, { "cell_type": "code", "execution_count": 291, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "generator" ] }, "execution_count": 291, "metadata": {}, "output_type": "execute_result" } ], "source": [ "it = iter(en)\n", "type(it)" ] }, { "cell_type": "code", "execution_count": 292, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0" ] }, "execution_count": 292, "metadata": {}, "output_type": "execute_result" } ], "source": [ "next(it)" ] }, { "cell_type": "code", "execution_count": 293, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "2" ] }, "execution_count": 293, "metadata": {}, "output_type": "execute_result" } ], "source": [ "next(it)" ] }, { "cell_type": "code", "execution_count": 294, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "4" ] }, "execution_count": 294, "metadata": {}, "output_type": "execute_result" } ], "source": [ "next(it)" ] }, { "cell_type": "code", "execution_count": 295, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "6" ] }, "execution_count": 295, "metadata": {}, "output_type": "execute_result" } ], "source": [ "next(it)" ] }, { "cell_type": "code", "execution_count": 296, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "8" ] }, "execution_count": 296, "metadata": {}, "output_type": "execute_result" } ], "source": [ "next(it)" ] }, { "cell_type": "code", "execution_count": 298, "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": "markdown", "metadata": {}, "source": [ "# Miscellaneous String Methods" ] }, { "cell_type": "code", "execution_count": 299, "metadata": {}, "outputs": [], "source": [ "s = 'joerg'" ] }, { "cell_type": "code", "execution_count": 301, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'JOERG'" ] }, "execution_count": 301, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s.upper()" ] }, { "cell_type": "code", "execution_count": 302, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'joerg'" ] }, "execution_count": 302, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s" ] }, { "cell_type": "code", "execution_count": 303, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'JOERG'" ] }, "execution_count": 303, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s = s.upper()\n", "s" ] }, { "cell_type": "code", "execution_count": 304, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 304, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s.isupper()" ] }, { "cell_type": "code", "execution_count": 305, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 305, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s.isalnum()" ] }, { "cell_type": "code", "execution_count": 307, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 307, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s.isalpha()" ] }, { "cell_type": "code", "execution_count": 309, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 309, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s.isdigit()" ] }, { "cell_type": "code", "execution_count": 310, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "2" ] }, "execution_count": 310, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s = 'mississppi'\n", "s.count('ss')" ] }, { "cell_type": "code", "execution_count": 312, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "2" ] }, "execution_count": 312, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s.find('ss')" ] }, { "cell_type": "code", "execution_count": 313, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "5" ] }, "execution_count": 313, "metadata": {}, "output_type": "execute_result" } ], "source": [ "pos = s.find('ss')\n", "pos = s.find('ss', pos+1)\n", "pos" ] }, { "cell_type": "code", "execution_count": 314, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "-1" ] }, "execution_count": 314, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s.find('xxx')" ] }, { "cell_type": "code", "execution_count": 315, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "jo\n" ] } ], "source": [ "if s.find('xxx'):\n", " print('jo')\n", "else:\n", " print('na')" ] }, { "cell_type": "code", "execution_count": 316, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "2" ] }, "execution_count": 316, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s.index('ss')" ] }, { "cell_type": "code", "execution_count": 318, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " substring not found\n" ] } ], "source": [ "try:\n", " s.index('xxx')\n", "except Exception as e:\n", " print(type(e), e)" ] }, { "cell_type": "code", "execution_count": 319, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 319, "metadata": {}, "output_type": "execute_result" } ], "source": [ "'hallo du'.startswith('hallo')" ] }, { "cell_type": "code", "execution_count": 320, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 320, "metadata": {}, "output_type": "execute_result" } ], "source": [ "'file.csv'.endswith('.csv')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## ``split`` und ``join``" ] }, { "cell_type": "code", "execution_count": 321, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['joerg', 'faschingbauer', '1037190666']" ] }, "execution_count": 321, "metadata": {}, "output_type": "execute_result" } ], "source": [ "line = 'joerg:faschingbauer:1037190666'\n", "fields = line.split(':')\n", "fields" ] }, { "cell_type": "code", "execution_count": 322, "metadata": {}, "outputs": [], "source": [ "firstname, lastname, svnr = line.split(':')" ] }, { "cell_type": "code", "execution_count": 323, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'joerg'" ] }, "execution_count": 323, "metadata": {}, "output_type": "execute_result" } ], "source": [ "firstname" ] }, { "cell_type": "code", "execution_count": 324, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['joerg', 'faschingbauer', '1037190666']" ] }, "execution_count": 324, "metadata": {}, "output_type": "execute_result" } ], "source": [ "fields" ] }, { "cell_type": "code", "execution_count": 325, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'joerg,faschingbauer,1037190666'" ] }, "execution_count": 325, "metadata": {}, "output_type": "execute_result" } ], "source": [ "','.join(fields)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## ``strip()``" ] }, { "cell_type": "code", "execution_count": 326, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'xxx'" ] }, "execution_count": 326, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s = ' xxx '\n", "s.strip()" ] }, { "cell_type": "code", "execution_count": 327, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "' xxx'" ] }, "execution_count": 327, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s.rstrip()" ] }, { "cell_type": "code", "execution_count": 328, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'xxx '" ] }, "execution_count": 328, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s.lstrip()" ] }, { "cell_type": "code", "execution_count": 329, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'xxxx'" ] }, "execution_count": 329, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s = ' a \\t xxxx \\n a '\n", "s.strip(' a\\t\\n')" ] }, { "cell_type": "code", "execution_count": 330, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "' a \\t xxxx'" ] }, "execution_count": 330, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s.rstrip(' a\\t\\n')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# File I/O" ] }, { "cell_type": "code", "execution_count": 331, "metadata": {}, "outputs": [], "source": [ "f = open('/etc/passwd')" ] }, { "cell_type": "code", "execution_count": 332, "metadata": {}, "outputs": [], "source": [ "f = open('/etc/passwd', encoding='ascii')" ] }, { "cell_type": "code", "execution_count": 333, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'root:x:0:0:root:/root:/bin/bash\\nbin:x:1:1:bin:/bin:/sbin/nologin\\ndaemon:x:2:2:daemon:/sbin:/sbin/nologin\\nadm:x:3:4:adm:/var/adm:/sbin/nologin\\nlp:x:4:7:lp:/var/spool/lpd:/sbin/nologin\\nsync:x:5:0:sync:/sbin:/bin/sync\\nshutdown:x:6:0:shutdown:/sbin:/sbin/shutdown\\nhalt:x:7:0:halt:/sbin:/sbin/halt\\nmail:x:8:12:mail:/var/spool/mail:/sbin/nologin\\noperator:x:11:0:operator:/root:/sbin/nologin\\ngames:x:12:100:games:/usr/games:/sbin/nologin\\nftp:x:14:50:FTP User:/var/ftp:/sbin/nologin\\nnobody:x:65534:65534:Kernel Overflow User:/:/sbin/nologin\\napache:x:48:48:Apache:/usr/share/httpd:/sbin/nologin\\nsystemd-network:x:192:192:systemd Network Management:/:/sbin/nologin\\nsystemd-coredump:x:999:997:systemd Core Dumper:/:/sbin/nologin\\nsystemd-resolve:x:193:193:systemd Resolver:/:/sbin/nologin\\nsystemd-oom:x:998:996:systemd Userspace OOM Killer:/:/sbin/nologin\\nsystemd-timesync:x:997:995:systemd Time Synchronization:/:/sbin/nologin\\ntss:x:59:59:Account used for TPM access:/dev/null:/sbin/nologin\\ndbus:x:81:81:System message bus:/:/sbin/nologin\\npolkitd:x:996:994:User for polkitd:/:/sbin/nologin\\navahi:x:70:70:Avahi mDNS/DNS-SD Stack:/var/run/avahi-daemon:/sbin/nologin\\nunbound:x:995:992:Unbound DNS resolver:/etc/unbound:/sbin/nologin\\ndnsmasq:x:994:991:Dnsmasq DHCP and DNS server:/var/lib/dnsmasq:/sbin/nologin\\nnm-openconnect:x:993:989:NetworkManager user for OpenConnect:/:/sbin/nologin\\nusbmuxd:x:113:113:usbmuxd user:/:/sbin/nologin\\ngluster:x:992:988:GlusterFS daemons:/run/gluster:/sbin/nologin\\nrtkit:x:172:172:RealtimeKit:/proc:/sbin/nologin\\npipewire:x:991:987:PipeWire System Daemon:/var/run/pipewire:/sbin/nologin\\ngeoclue:x:990:986:User for geoclue:/var/lib/geoclue:/sbin/nologin\\nchrony:x:989:984::/var/lib/chrony:/sbin/nologin\\nsaslauth:x:988:76:Saslauthd user:/run/saslauthd:/sbin/nologin\\nradvd:x:75:75:radvd user:/:/sbin/nologin\\nrpc:x:32:32:Rpcbind Daemon:/var/lib/rpcbind:/sbin/nologin\\nqemu:x:107:107:qemu user:/:/sbin/nologin\\nopenvpn:x:987:982:OpenVPN:/etc/openvpn:/sbin/nologin\\nnm-openvpn:x:986:981:Default user for running openvpn spawned by NetworkManager:/:/sbin/nologin\\ncolord:x:985:980:User for colord:/var/lib/colord:/sbin/nologin\\nrpcuser:x:29:29:RPC Service User:/var/lib/nfs:/sbin/nologin\\nabrt:x:173:173::/etc/abrt:/sbin/nologin\\nflatpak:x:984:979:User for flatpak system helper:/:/sbin/nologin\\ngdm:x:42:42::/var/lib/gdm:/sbin/nologin\\ngnome-initial-setup:x:983:978::/run/gnome-initial-setup/:/sbin/nologin\\nvboxadd:x:982:1::/var/run/vboxadd:/sbin/nologin\\nsshd:x:74:74:Privilege-separated SSH:/usr/share/empty.sshd:/sbin/nologin\\ntcpdump:x:72:72::/:/sbin/nologin\\njfasch:x:1000:1000:Joerg Faschingbauer:/home/jfasch:/bin/bash\\nmosquitto:x:981:974:Mosquitto Broker:/etc/mosquitto:/sbin/nologin\\nsomeone-else:x:1001:1001::/home/someone-else:/bin/bash\\n'" ] }, "execution_count": 333, "metadata": {}, "output_type": "execute_result" } ], "source": [ "f.read()" ] }, { "cell_type": "code", "execution_count": 334, "metadata": {}, "outputs": [], "source": [ "f = open('/etc/passwd', encoding='ascii')" ] }, { "cell_type": "code", "execution_count": 335, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'root:x:0:0:root'" ] }, "execution_count": 335, "metadata": {}, "output_type": "execute_result" } ], "source": [ "f.read(15)" ] }, { "cell_type": "code", "execution_count": 336, "metadata": {}, "outputs": [], "source": [ "f = open('/etc/passwd', encoding='ascii')" ] }, { "cell_type": "code", "execution_count": 337, "metadata": {}, "outputs": [], "source": [ "lines = f.readlines()" ] }, { "cell_type": "code", "execution_count": 339, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['root:x:0:0:root:/root:/bin/bash\\n',\n", " 'bin:x:1:1:bin:/bin:/sbin/nologin\\n',\n", " 'daemon:x:2:2:daemon:/sbin:/sbin/nologin\\n',\n", " 'adm:x:3:4:adm:/var/adm:/sbin/nologin\\n',\n", " 'lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin\\n',\n", " 'sync:x:5:0:sync:/sbin:/bin/sync\\n',\n", " 'shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown\\n',\n", " 'halt:x:7:0:halt:/sbin:/sbin/halt\\n',\n", " 'mail:x:8:12:mail:/var/spool/mail:/sbin/nologin\\n',\n", " 'operator:x:11:0:operator:/root:/sbin/nologin\\n',\n", " 'games:x:12:100:games:/usr/games:/sbin/nologin\\n',\n", " 'ftp:x:14:50:FTP User:/var/ftp:/sbin/nologin\\n',\n", " 'nobody:x:65534:65534:Kernel Overflow User:/:/sbin/nologin\\n',\n", " 'apache:x:48:48:Apache:/usr/share/httpd:/sbin/nologin\\n',\n", " 'systemd-network:x:192:192:systemd Network Management:/:/sbin/nologin\\n',\n", " 'systemd-coredump:x:999:997:systemd Core Dumper:/:/sbin/nologin\\n',\n", " 'systemd-resolve:x:193:193:systemd Resolver:/:/sbin/nologin\\n',\n", " 'systemd-oom:x:998:996:systemd Userspace OOM Killer:/:/sbin/nologin\\n',\n", " 'systemd-timesync:x:997:995:systemd Time Synchronization:/:/sbin/nologin\\n',\n", " 'tss:x:59:59:Account used for TPM access:/dev/null:/sbin/nologin\\n',\n", " 'dbus:x:81:81:System message bus:/:/sbin/nologin\\n',\n", " 'polkitd:x:996:994:User for polkitd:/:/sbin/nologin\\n',\n", " 'avahi:x:70:70:Avahi mDNS/DNS-SD Stack:/var/run/avahi-daemon:/sbin/nologin\\n',\n", " 'unbound:x:995:992:Unbound DNS resolver:/etc/unbound:/sbin/nologin\\n',\n", " 'dnsmasq:x:994:991:Dnsmasq DHCP and DNS server:/var/lib/dnsmasq:/sbin/nologin\\n',\n", " 'nm-openconnect:x:993:989:NetworkManager user for OpenConnect:/:/sbin/nologin\\n',\n", " 'usbmuxd:x:113:113:usbmuxd user:/:/sbin/nologin\\n',\n", " 'gluster:x:992:988:GlusterFS daemons:/run/gluster:/sbin/nologin\\n',\n", " 'rtkit:x:172:172:RealtimeKit:/proc:/sbin/nologin\\n',\n", " 'pipewire:x:991:987:PipeWire System Daemon:/var/run/pipewire:/sbin/nologin\\n',\n", " 'geoclue:x:990:986:User for geoclue:/var/lib/geoclue:/sbin/nologin\\n',\n", " 'chrony:x:989:984::/var/lib/chrony:/sbin/nologin\\n',\n", " 'saslauth:x:988:76:Saslauthd user:/run/saslauthd:/sbin/nologin\\n',\n", " 'radvd:x:75:75:radvd user:/:/sbin/nologin\\n',\n", " 'rpc:x:32:32:Rpcbind Daemon:/var/lib/rpcbind:/sbin/nologin\\n',\n", " 'qemu:x:107:107:qemu user:/:/sbin/nologin\\n',\n", " 'openvpn:x:987:982:OpenVPN:/etc/openvpn:/sbin/nologin\\n',\n", " 'nm-openvpn:x:986:981:Default user for running openvpn spawned by NetworkManager:/:/sbin/nologin\\n',\n", " 'colord:x:985:980:User for colord:/var/lib/colord:/sbin/nologin\\n',\n", " 'rpcuser:x:29:29:RPC Service User:/var/lib/nfs:/sbin/nologin\\n',\n", " 'abrt:x:173:173::/etc/abrt:/sbin/nologin\\n',\n", " 'flatpak:x:984:979:User for flatpak system helper:/:/sbin/nologin\\n',\n", " 'gdm:x:42:42::/var/lib/gdm:/sbin/nologin\\n',\n", " 'gnome-initial-setup:x:983:978::/run/gnome-initial-setup/:/sbin/nologin\\n',\n", " 'vboxadd:x:982:1::/var/run/vboxadd:/sbin/nologin\\n',\n", " 'sshd:x:74:74:Privilege-separated SSH:/usr/share/empty.sshd:/sbin/nologin\\n',\n", " 'tcpdump:x:72:72::/:/sbin/nologin\\n',\n", " 'jfasch:x:1000:1000:Joerg Faschingbauer:/home/jfasch:/bin/bash\\n',\n", " 'mosquitto:x:981:974:Mosquitto Broker:/etc/mosquitto:/sbin/nologin\\n',\n", " 'someone-else:x:1001:1001::/home/someone-else:/bin/bash\\n']" ] }, "execution_count": 339, "metadata": {}, "output_type": "execute_result" } ], "source": [ "lines" ] }, { "cell_type": "code", "execution_count": 340, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "root:x:0:0:root:/root:/bin/bash\n", "\n", "bin:x:1:1:bin:/bin:/sbin/nologin\n", "\n", "daemon:x:2:2:daemon:/sbin:/sbin/nologin\n", "\n", "adm:x:3:4:adm:/var/adm:/sbin/nologin\n", "\n", "lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin\n", "\n", "sync:x:5:0:sync:/sbin:/bin/sync\n", "\n", "shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown\n", "\n", "halt:x:7:0:halt:/sbin:/sbin/halt\n", "\n", "mail:x:8:12:mail:/var/spool/mail:/sbin/nologin\n", "\n", "operator:x:11:0:operator:/root:/sbin/nologin\n", "\n", "games:x:12:100:games:/usr/games:/sbin/nologin\n", "\n", "ftp:x:14:50:FTP User:/var/ftp:/sbin/nologin\n", "\n", "nobody:x:65534:65534:Kernel Overflow User:/:/sbin/nologin\n", "\n", "apache:x:48:48:Apache:/usr/share/httpd:/sbin/nologin\n", "\n", "systemd-network:x:192:192:systemd Network Management:/:/sbin/nologin\n", "\n", "systemd-coredump:x:999:997:systemd Core Dumper:/:/sbin/nologin\n", "\n", "systemd-resolve:x:193:193:systemd Resolver:/:/sbin/nologin\n", "\n", "systemd-oom:x:998:996:systemd Userspace OOM Killer:/:/sbin/nologin\n", "\n", "systemd-timesync:x:997:995:systemd Time Synchronization:/:/sbin/nologin\n", "\n", "tss:x:59:59:Account used for TPM access:/dev/null:/sbin/nologin\n", "\n", "dbus:x:81:81:System message bus:/:/sbin/nologin\n", "\n", "polkitd:x:996:994:User for polkitd:/:/sbin/nologin\n", "\n", "avahi:x:70:70:Avahi mDNS/DNS-SD Stack:/var/run/avahi-daemon:/sbin/nologin\n", "\n", "unbound:x:995:992:Unbound DNS resolver:/etc/unbound:/sbin/nologin\n", "\n", "dnsmasq:x:994:991:Dnsmasq DHCP and DNS server:/var/lib/dnsmasq:/sbin/nologin\n", "\n", "nm-openconnect:x:993:989:NetworkManager user for OpenConnect:/:/sbin/nologin\n", "\n", "usbmuxd:x:113:113:usbmuxd user:/:/sbin/nologin\n", "\n", "gluster:x:992:988:GlusterFS daemons:/run/gluster:/sbin/nologin\n", "\n", "rtkit:x:172:172:RealtimeKit:/proc:/sbin/nologin\n", "\n", "pipewire:x:991:987:PipeWire System Daemon:/var/run/pipewire:/sbin/nologin\n", "\n", "geoclue:x:990:986:User for geoclue:/var/lib/geoclue:/sbin/nologin\n", "\n", "chrony:x:989:984::/var/lib/chrony:/sbin/nologin\n", "\n", "saslauth:x:988:76:Saslauthd user:/run/saslauthd:/sbin/nologin\n", "\n", "radvd:x:75:75:radvd user:/:/sbin/nologin\n", "\n", "rpc:x:32:32:Rpcbind Daemon:/var/lib/rpcbind:/sbin/nologin\n", "\n", "qemu:x:107:107:qemu user:/:/sbin/nologin\n", "\n", "openvpn:x:987:982:OpenVPN:/etc/openvpn:/sbin/nologin\n", "\n", "nm-openvpn:x:986:981:Default user for running openvpn spawned by NetworkManager:/:/sbin/nologin\n", "\n", "colord:x:985:980:User for colord:/var/lib/colord:/sbin/nologin\n", "\n", "rpcuser:x:29:29:RPC Service User:/var/lib/nfs:/sbin/nologin\n", "\n", "abrt:x:173:173::/etc/abrt:/sbin/nologin\n", "\n", "flatpak:x:984:979:User for flatpak system helper:/:/sbin/nologin\n", "\n", "gdm:x:42:42::/var/lib/gdm:/sbin/nologin\n", "\n", "gnome-initial-setup:x:983:978::/run/gnome-initial-setup/:/sbin/nologin\n", "\n", "vboxadd:x:982:1::/var/run/vboxadd:/sbin/nologin\n", "\n", "sshd:x:74:74:Privilege-separated SSH:/usr/share/empty.sshd:/sbin/nologin\n", "\n", "tcpdump:x:72:72::/:/sbin/nologin\n", "\n", "jfasch:x:1000:1000:Joerg Faschingbauer:/home/jfasch:/bin/bash\n", "\n", "mosquitto:x:981:974:Mosquitto Broker:/etc/mosquitto:/sbin/nologin\n", "\n", "someone-else:x:1001:1001::/home/someone-else:/bin/bash\n", "\n" ] } ], "source": [ "for line in lines:\n", " print(line)" ] }, { "cell_type": "code", "execution_count": 341, "metadata": {}, "outputs": [], "source": [ "f = open('/etc/passwd', encoding='ascii')" ] }, { "cell_type": "code", "execution_count": 342, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "root:x:0:0:root:/root:/bin/bash\n", "\n", "bin:x:1:1:bin:/bin:/sbin/nologin\n", "\n", "daemon:x:2:2:daemon:/sbin:/sbin/nologin\n", "\n", "adm:x:3:4:adm:/var/adm:/sbin/nologin\n", "\n", "lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin\n", "\n", "sync:x:5:0:sync:/sbin:/bin/sync\n", "\n", "shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown\n", "\n", "halt:x:7:0:halt:/sbin:/sbin/halt\n", "\n", "mail:x:8:12:mail:/var/spool/mail:/sbin/nologin\n", "\n", "operator:x:11:0:operator:/root:/sbin/nologin\n", "\n", "games:x:12:100:games:/usr/games:/sbin/nologin\n", "\n", "ftp:x:14:50:FTP User:/var/ftp:/sbin/nologin\n", "\n", "nobody:x:65534:65534:Kernel Overflow User:/:/sbin/nologin\n", "\n", "apache:x:48:48:Apache:/usr/share/httpd:/sbin/nologin\n", "\n", "systemd-network:x:192:192:systemd Network Management:/:/sbin/nologin\n", "\n", "systemd-coredump:x:999:997:systemd Core Dumper:/:/sbin/nologin\n", "\n", "systemd-resolve:x:193:193:systemd Resolver:/:/sbin/nologin\n", "\n", "systemd-oom:x:998:996:systemd Userspace OOM Killer:/:/sbin/nologin\n", "\n", "systemd-timesync:x:997:995:systemd Time Synchronization:/:/sbin/nologin\n", "\n", "tss:x:59:59:Account used for TPM access:/dev/null:/sbin/nologin\n", "\n", "dbus:x:81:81:System message bus:/:/sbin/nologin\n", "\n", "polkitd:x:996:994:User for polkitd:/:/sbin/nologin\n", "\n", "avahi:x:70:70:Avahi mDNS/DNS-SD Stack:/var/run/avahi-daemon:/sbin/nologin\n", "\n", "unbound:x:995:992:Unbound DNS resolver:/etc/unbound:/sbin/nologin\n", "\n", "dnsmasq:x:994:991:Dnsmasq DHCP and DNS server:/var/lib/dnsmasq:/sbin/nologin\n", "\n", "nm-openconnect:x:993:989:NetworkManager user for OpenConnect:/:/sbin/nologin\n", "\n", "usbmuxd:x:113:113:usbmuxd user:/:/sbin/nologin\n", "\n", "gluster:x:992:988:GlusterFS daemons:/run/gluster:/sbin/nologin\n", "\n", "rtkit:x:172:172:RealtimeKit:/proc:/sbin/nologin\n", "\n", "pipewire:x:991:987:PipeWire System Daemon:/var/run/pipewire:/sbin/nologin\n", "\n", "geoclue:x:990:986:User for geoclue:/var/lib/geoclue:/sbin/nologin\n", "\n", "chrony:x:989:984::/var/lib/chrony:/sbin/nologin\n", "\n", "saslauth:x:988:76:Saslauthd user:/run/saslauthd:/sbin/nologin\n", "\n", "radvd:x:75:75:radvd user:/:/sbin/nologin\n", "\n", "rpc:x:32:32:Rpcbind Daemon:/var/lib/rpcbind:/sbin/nologin\n", "\n", "qemu:x:107:107:qemu user:/:/sbin/nologin\n", "\n", "openvpn:x:987:982:OpenVPN:/etc/openvpn:/sbin/nologin\n", "\n", "nm-openvpn:x:986:981:Default user for running openvpn spawned by NetworkManager:/:/sbin/nologin\n", "\n", "colord:x:985:980:User for colord:/var/lib/colord:/sbin/nologin\n", "\n", "rpcuser:x:29:29:RPC Service User:/var/lib/nfs:/sbin/nologin\n", "\n", "abrt:x:173:173::/etc/abrt:/sbin/nologin\n", "\n", "flatpak:x:984:979:User for flatpak system helper:/:/sbin/nologin\n", "\n", "gdm:x:42:42::/var/lib/gdm:/sbin/nologin\n", "\n", "gnome-initial-setup:x:983:978::/run/gnome-initial-setup/:/sbin/nologin\n", "\n", "vboxadd:x:982:1::/var/run/vboxadd:/sbin/nologin\n", "\n", "sshd:x:74:74:Privilege-separated SSH:/usr/share/empty.sshd:/sbin/nologin\n", "\n", "tcpdump:x:72:72::/:/sbin/nologin\n", "\n", "jfasch:x:1000:1000:Joerg Faschingbauer:/home/jfasch:/bin/bash\n", "\n", "mosquitto:x:981:974:Mosquitto Broker:/etc/mosquitto:/sbin/nologin\n", "\n", "someone-else:x:1001:1001::/home/someone-else:/bin/bash\n", "\n" ] } ], "source": [ "for line in f:\n", " print(line)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# ``dict`` vs. ``OrderedDict``" ] }, { "cell_type": "code", "execution_count": 343, "metadata": {}, "outputs": [], "source": [ "d = {}" ] }, { "cell_type": "code", "execution_count": 344, "metadata": {}, "outputs": [], "source": [ "d['five'] = 5" ] }, { "cell_type": "code", "execution_count": 345, "metadata": {}, "outputs": [], "source": [ "d['three'] = 3" ] }, { "cell_type": "code", "execution_count": 346, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "five\n", "three\n" ] } ], "source": [ "for k in d.keys():\n", " print(k)" ] }, { "cell_type": "code", "execution_count": 348, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "OrderedDict([('five', 5), ('three', 3)])" ] }, "execution_count": 348, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import collections\n", "\n", "od = collections.OrderedDict(d.items())\n", "od" ] }, { "cell_type": "code", "execution_count": 349, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "5" ] }, "execution_count": 349, "metadata": {}, "output_type": "execute_result" } ], "source": [ "od['five']" ] }, { "cell_type": "code", "execution_count": 351, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "None\n" ] } ], "source": [ "found = od.get('ten')\n", "print(found)" ] }, { "cell_type": "code", "execution_count": 352, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "five\n", "three\n" ] } ], "source": [ "for k in od.keys():\n", " print(k)" ] }, { "cell_type": "code", "execution_count": 353, "metadata": {}, "outputs": [], "source": [ "od.move_to_end('five')" ] }, { "cell_type": "code", "execution_count": 354, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "three\n", "five\n" ] } ], "source": [ "for k in od.keys():\n", " print(k)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Object Oriented Programming" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Duck Typing" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "class ThermometerA:\n", " def __init__(self, t):\n", " self.temp = t\n", " def get_temperature(self):\n", " return self.temp" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "class ThermometerB:\n", " def __init__(self, t):\n", " self.temp = t\n", " def get_temperature(self):\n", " return self.temp" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "10" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a = ThermometerA(10)\n", "a.get_temperature()" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "20" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "b = ThermometerB(20)\n", "b.get_temperature()" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [], "source": [ "def get_average_temperature(th_list):\n", " avg = 0\n", " for t in th_list:\n", " avg += t.get_temperature()\n", " return avg/len(th_list)" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "15.0" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "get_average_temperature([a, b])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Interfaces" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [], "source": [ "class Thermometer:\n", " def get_temperature(self):\n", " assert False, 'this must be implemented'" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [], "source": [ "class ThermometerA(Thermometer):\n", " def __init__(self, t):\n", " self.temp = t\n", " def get_temperature(self):\n", " return self.temp" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [], "source": [ "class ThermometerB:\n", " def __init__(self, t):\n", " self.temp = t\n", " def get_temperature(self):\n", " return self.temp" ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "10" ] }, "execution_count": 26, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a = ThermometerA(10)\n", "a.get_temperature()" ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "100" ] }, "execution_count": 28, "metadata": {}, "output_type": "execute_result" } ], "source": [ "b = ThermometerB(100)\n", "b.get_temperature()" ] }, { "cell_type": "code", "execution_count": 31, "metadata": {}, "outputs": [], "source": [ "def get_average_temperature(th_list):\n", " avg = 0\n", " for t in th_list:\n", " if not isinstance(t, Thermometer):\n", " raise TypeError(f'{t} is not a Thermometer')\n", " avg += t.get_temperature()\n", " return avg/len(th_list)" ] }, { "cell_type": "code", "execution_count": 32, "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "<__main__.ThermometerB object at 0x7fac83797be0> is not a Thermometer", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m/tmp/ipykernel_9164/859664274.py\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mget_average_temperature\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0ma\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0mb\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;32m/tmp/ipykernel_9164/2942790015.py\u001b[0m in \u001b[0;36mget_average_temperature\u001b[0;34m(th_list)\u001b[0m\n\u001b[1;32m 3\u001b[0m \u001b[0;32mfor\u001b[0m \u001b[0mt\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mth_list\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 4\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0;32mnot\u001b[0m \u001b[0misinstance\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mt\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mThermometer\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 5\u001b[0;31m \u001b[0;32mraise\u001b[0m \u001b[0mTypeError\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34mf'{t} is not a Thermometer'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 6\u001b[0m \u001b[0mavg\u001b[0m \u001b[0;34m+=\u001b[0m \u001b[0mt\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mget_temperature\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 7\u001b[0m \u001b[0;32mreturn\u001b[0m \u001b[0mavg\u001b[0m\u001b[0;34m/\u001b[0m\u001b[0mlen\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mth_list\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", "\u001b[0;31mTypeError\u001b[0m: <__main__.ThermometerB object at 0x7fac83797be0> is not a Thermometer" ] } ], "source": [ "get_average_temperature([a,b])" ] }, { "cell_type": "code", "execution_count": 34, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 34, "metadata": {}, "output_type": "execute_result" } ], "source": [ "issubclass(ThermometerA, Thermometer)" ] }, { "cell_type": "code", "execution_count": 35, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 35, "metadata": {}, "output_type": "execute_result" } ], "source": [ "issubclass(ThermometerB, Thermometer)" ] }, { "cell_type": "code", "execution_count": 36, "metadata": {}, "outputs": [], "source": [ "class ThermometerB(Thermometer):\n", " def __init__(self, t):\n", " self.temp = t\n", " def get_temperature(self):\n", " return self.temp" ] }, { "cell_type": "code", "execution_count": 38, "metadata": {}, "outputs": [], "source": [ "b = ThermometerB(1000)" ] }, { "cell_type": "code", "execution_count": 39, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "505.0" ] }, "execution_count": 39, "metadata": {}, "output_type": "execute_result" } ], "source": [ "get_average_temperature([a, b])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Implementation Inheritance" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [], "source": [ "class Thermometer:\n", " def get_temperature(self):\n", " assert False, 'this must be implemented'" ] }, { "cell_type": "code", "execution_count": 42, "metadata": {}, "outputs": [], "source": [ "class ThermometerA(Thermometer):\n", " def __init__(self, name, t):\n", " self.name = name\n", " self.temp = t\n", " def get_temperature(self):\n", " return self.temp" ] }, { "cell_type": "code", "execution_count": 41, "metadata": {}, "outputs": [], "source": [ "class ThermometerB(Thermometer):\n", " def __init__(self, name, t):\n", " self.name = name\n", " self.temp = t\n", " def get_temperature(self):\n", " return self.temp" ] }, { "cell_type": "code", "execution_count": 45, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Ein A Thermometer'" ] }, "execution_count": 45, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a = ThermometerA(name='Ein A Thermometer', t=10)\n", "a.name" ] }, { "cell_type": "code", "execution_count": 47, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Ein B Thermometer'" ] }, "execution_count": 47, "metadata": {}, "output_type": "execute_result" } ], "source": [ "b = ThermometerB(name='Ein B Thermometer', t=1000)\n", "b.name" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Nun aber fassen wir ``name`` in die Basisklasse" ] }, { "cell_type": "code", "execution_count": 51, "metadata": {}, "outputs": [], "source": [ "class Thermometer:\n", " def __init__(self, name):\n", " self.name = name\n", " def get_temperature(self):\n", " assert False, 'this must be implemented'" ] }, { "cell_type": "code", "execution_count": 59, "metadata": {}, "outputs": [], "source": [ "class ThermometerA(Thermometer):\n", " def __init__(self, name, t):\n", " super().__init__(name)\n", " self.temp = t\n", " def get_temperature(self):\n", " return self.temp" ] }, { "cell_type": "code", "execution_count": 63, "metadata": {}, "outputs": [], "source": [ "class ThermometerB(Thermometer):\n", " def __init__(self, name, t):\n", " super().__init__(name)\n", " self.temp = t\n", " def get_temperature(self):\n", " return self.temp" ] }, { "cell_type": "code", "execution_count": 60, "metadata": {}, "outputs": [], "source": [ "a = ThermometerA(name='Joerg', t=10)" ] }, { "cell_type": "code", "execution_count": 61, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'name': 'Joerg', 'temp': 10}" ] }, "execution_count": 61, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a.__dict__" ] }, { "cell_type": "code", "execution_count": 64, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Joerg'" ] }, "execution_count": 64, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a.name" ] }, { "cell_type": "code", "execution_count": 65, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Hansi'" ] }, "execution_count": 65, "metadata": {}, "output_type": "execute_result" } ], "source": [ "b = ThermometerB('Hansi', 100)\n", "b.name" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Method Resolution Order (MRO), and ``super()``" ] }, { "cell_type": "code", "execution_count": 66, "metadata": {}, "outputs": [], "source": [ "class Base:\n", " def f(self):\n", " print('Base.f')" ] }, { "cell_type": "code", "execution_count": 72, "metadata": {}, "outputs": [], "source": [ "class Level2_1(Base):\n", " def f(self):\n", " print('Level2_1.f')\n", " super().f()" ] }, { "cell_type": "code", "execution_count": 74, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Level2_1.f\n", "Base.f\n" ] } ], "source": [ "l21 = Level2_1()\n", "l21.f()" ] }, { "cell_type": "code", "execution_count": 75, "metadata": {}, "outputs": [], "source": [ "class Level2_2(Base):\n", " def f(self):\n", " print('level2_2.f')\n", " super().f()" ] }, { "cell_type": "code", "execution_count": 78, "metadata": {}, "outputs": [], "source": [ "class Level3(Level2_1, Level2_2):\n", " def f(self):\n", " print('Level3.f')\n", " super().f()" ] }, { "cell_type": "code", "execution_count": 79, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Level3.f\n", "Level2_1.f\n", "level2_2.f\n", "Base.f\n" ] } ], "source": [ "l3 = Level3()\n", "l3.f()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### ``__bases__``" ] }, { "cell_type": "code", "execution_count": 80, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(object,)" ] }, "execution_count": 80, "metadata": {}, "output_type": "execute_result" } ], "source": [ "Base.__bases__" ] }, { "cell_type": "code", "execution_count": 81, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(__main__.Base,)" ] }, "execution_count": 81, "metadata": {}, "output_type": "execute_result" } ], "source": [ "Level2_1.__bases__" ] }, { "cell_type": "code", "execution_count": 83, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(__main__.Base,)" ] }, "execution_count": 83, "metadata": {}, "output_type": "execute_result" } ], "source": [ "Level2_2.__bases__" ] }, { "cell_type": "code", "execution_count": 85, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(__main__.Level2_1, __main__.Level2_2)" ] }, "execution_count": 85, "metadata": {}, "output_type": "execute_result" } ], "source": [ "Level3.__bases__" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### ``__mro__``" ] }, { "cell_type": "code", "execution_count": 86, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(__main__.Level3, __main__.Level2_1, __main__.Level2_2, __main__.Base, object)" ] }, "execution_count": 86, "metadata": {}, "output_type": "execute_result" } ], "source": [ "Level3.__mro__" ] }, { "cell_type": "code", "execution_count": 87, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(__main__.Level2_1, __main__.Base, object)" ] }, "execution_count": 87, "metadata": {}, "output_type": "execute_result" } ], "source": [ "Level2_1.__mro__" ] }, { "cell_type": "code", "execution_count": 88, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(__main__.Base, object)" ] }, "execution_count": 88, "metadata": {}, "output_type": "execute_result" } ], "source": [ "Base.__mro__" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Object Layout (``self``)" ] }, { "cell_type": "code", "execution_count": 89, "metadata": {}, "outputs": [], "source": [ "class Jedi:\n", " def f(self):\n", " self.force = 15" ] }, { "cell_type": "code", "execution_count": 94, "metadata": {}, "outputs": [], "source": [ "class Luke(Jedi):\n", " def f(self):\n", " self.blueeyes = True\n", " super().f()" ] }, { "cell_type": "code", "execution_count": 97, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{}" ] }, "execution_count": 97, "metadata": {}, "output_type": "execute_result" } ], "source": [ "luke = Luke()\n", "luke.__dict__" ] }, { "cell_type": "code", "execution_count": 96, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'blueeyes': True, 'force': 15}" ] }, "execution_count": 96, "metadata": {}, "output_type": "execute_result" } ], "source": [ "luke.f()\n", "luke.__dict__" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## More from OO" ] }, { "cell_type": "code", "execution_count": 111, "metadata": {}, "outputs": [], "source": [ "class Robot:\n", " def __init__(self, name):\n", " self.name = name\n", " def __str__(self):\n", " return 'Robot name is: ' + self.name" ] }, { "cell_type": "code", "execution_count": 112, "metadata": {}, "outputs": [], "source": [ "class Droid(Robot):\n", " def __str__(self):\n", " return 'Droid name is: ' + self.name" ] }, { "cell_type": "code", "execution_count": 114, "metadata": {}, "outputs": [], "source": [ "d = Droid('R2D2')" ] }, { "cell_type": "code", "execution_count": 117, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'R2D2'" ] }, "execution_count": 117, "metadata": {}, "output_type": "execute_result" } ], "source": [ "d.name" ] }, { "cell_type": "code", "execution_count": 119, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Droid name is: R2D2\n" ] } ], "source": [ "print(d)" ] }, { "cell_type": "code", "execution_count": 120, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Droid name is: R2D2'" ] }, "execution_count": 120, "metadata": {}, "output_type": "execute_result" } ], "source": [ "d.__str__()" ] }, { "cell_type": "code", "execution_count": 121, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'name': 'R2D2'}" ] }, "execution_count": 121, "metadata": {}, "output_type": "execute_result" } ], "source": [ "d.__dict__" ] }, { "cell_type": "code", "execution_count": 122, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'R2D2'" ] }, "execution_count": 122, "metadata": {}, "output_type": "execute_result" } ], "source": [ "d.__dict__['name']" ] }, { "cell_type": "code", "execution_count": 123, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'R2D2'" ] }, "execution_count": 123, "metadata": {}, "output_type": "execute_result" } ], "source": [ "d.name" ] }, { "cell_type": "code", "execution_count": 124, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "type" ] }, "execution_count": 124, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(Droid)" ] }, { "cell_type": "code", "execution_count": 125, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "mappingproxy({'__module__': '__main__',\n", " '__str__': ,\n", " '__doc__': None})" ] }, "execution_count": 125, "metadata": {}, "output_type": "execute_result" } ], "source": [ "Droid.__dict__" ] }, { "cell_type": "code", "execution_count": 126, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(__main__.Robot,)" ] }, "execution_count": 126, "metadata": {}, "output_type": "execute_result" } ], "source": [ "Droid.__bases__" ] }, { "cell_type": "code", "execution_count": 127, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "mappingproxy({'__module__': '__main__',\n", " '__init__': ,\n", " '__str__': ,\n", " '__dict__': ,\n", " '__weakref__': ,\n", " '__doc__': None})" ] }, "execution_count": 127, "metadata": {}, "output_type": "execute_result" } ], "source": [ "Droid.__bases__[0].__dict__" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Operator Overloading" ] }, { "cell_type": "code", "execution_count": 155, "metadata": {}, "outputs": [], "source": [ "class Integer:\n", " def __init__(self, value):\n", " print('__init__')\n", " self.value = value\n", " def __str__(self):\n", " print('__str__')\n", " return str(self.value)\n", " def __lt__(self, rhs):\n", " if self.value < rhs.value:\n", " return True\n", " else:\n", " return False\n", " def __add__(self, rhs):\n", " return Integer(self.value + rhs.value)" ] }, { "cell_type": "code", "execution_count": 149, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "__init__\n", "__str__\n", "42\n" ] } ], "source": [ "i = Integer(42)\n", "print(i)" ] }, { "cell_type": "code", "execution_count": 150, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "__init__\n" ] } ], "source": [ "j = Integer(666)" ] }, { "cell_type": "code", "execution_count": 152, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 152, "metadata": {}, "output_type": "execute_result" } ], "source": [ "i < j" ] }, { "cell_type": "code", "execution_count": 156, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "__init__\n", "__str__\n", "708\n" ] } ], "source": [ "s = i + j\n", "print(s)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Calling Base Class Constructor (Many Ways)" ] }, { "cell_type": "code", "execution_count": 173, "metadata": {}, "outputs": [], "source": [ "class Base:\n", " def __init__(self, val):\n", " print('Base.__init__')\n", " self.val = val" ] }, { "cell_type": "code", "execution_count": 174, "metadata": {}, "outputs": [], "source": [ "class DerivedNoCtor(Base):\n", " pass" ] }, { "cell_type": "code", "execution_count": 175, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Base.__init__\n" ] } ], "source": [ "dnoctor = DerivedNoCtor(10)" ] }, { "cell_type": "code", "execution_count": 176, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "10" ] }, "execution_count": 176, "metadata": {}, "output_type": "execute_result" } ], "source": [ "dnoctor.val" ] }, { "cell_type": "code", "execution_count": 181, "metadata": {}, "outputs": [], "source": [ "class DerivedCtorCallingSuper(Base):\n", " def __init__(self, val):\n", " print('DerivedCtorCallingSuper.__init__')\n", " super().__init__(val)" ] }, { "cell_type": "code", "execution_count": 180, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "DerivedCtorCallingSuper.__init__\n", "Base.__init__\n" ] } ], "source": [ "o = DerivedCtorCallingSuper(666)" ] }, { "cell_type": "code", "execution_count": 183, "metadata": {}, "outputs": [], "source": [ "class DerivedCtorCallingBaseCtor(Base):\n", " def __init__(self, val):\n", " print('DerivedCtorCallingBaseCtor.__init__')\n", " Base.__init__(self, val)" ] }, { "cell_type": "code", "execution_count": 184, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "DerivedCtorCallingBaseCtor.__init__\n", "Base.__init__\n" ] } ], "source": [ "o = DerivedCtorCallingBaseCtor(42)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Name Mangling (\"private\" Members)" ] }, { "cell_type": "code", "execution_count": 185, "metadata": {}, "outputs": [], "source": [ "class User:\n", " def __init__(self, firstname, lastname):\n", " self.__firstname = firstname\n", " self.__lastname = lastname" ] }, { "cell_type": "code", "execution_count": 188, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " 'User' object has no attribute '__firstname'\n" ] } ], "source": [ "try:\n", " u.__firstname\n", "except Exception as e:\n", " print(type(e), e)" ] }, { "cell_type": "code", "execution_count": 186, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'_User__firstname': 'Joerg', '_User__lastname': 'Faschingbauer'}" ] }, "execution_count": 186, "metadata": {}, "output_type": "execute_result" } ], "source": [ "u = User(\"Joerg\", \"Faschingbauer\")\n", "u.__dict__" ] }, { "cell_type": "code", "execution_count": 189, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Joerg'" ] }, "execution_count": 189, "metadata": {}, "output_type": "execute_result" } ], "source": [ "u._User__firstname" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Properties" ] }, { "cell_type": "code", "execution_count": 200, "metadata": {}, "outputs": [], "source": [ "class User:\n", " def __init__(self, firstname, lastname):\n", " self.__firstname = firstname\n", " self.__lastname = lastname\n", " @property\n", " def firstname(self):\n", " return self.__firstname\n", " \n", " @property\n", " def lastname(self):\n", " return self.__lastname\n", " \n", " @property\n", " def name(self):\n", " return self.__firstname + ' ' + self.__lastname" ] }, { "cell_type": "code", "execution_count": 201, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Joerg Faschingbauer'" ] }, "execution_count": 201, "metadata": {}, "output_type": "execute_result" } ], "source": [ "u = User(\"Joerg\", \"Faschingbauer\")\n", "u.name" ] }, { "cell_type": "code", "execution_count": 202, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Joerg'" ] }, "execution_count": 202, "metadata": {}, "output_type": "execute_result" } ], "source": [ "u.firstname" ] }, { "cell_type": "code", "execution_count": 204, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Faschingbauer'" ] }, "execution_count": 204, "metadata": {}, "output_type": "execute_result" } ], "source": [ "u.lastname" ] }, { "cell_type": "code", "execution_count": 206, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " can't set attribute\n" ] } ], "source": [ "try:\n", " u.lastname = 'Huber'\n", "except Exception as e:\n", " print(type(e), e)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Yet Another Example From Udemy" ] }, { "cell_type": "code", "execution_count": 286, "metadata": {}, "outputs": [], "source": [ "class Jedi:\n", " LightSaber = True" ] }, { "cell_type": "code", "execution_count": 287, "metadata": {}, "outputs": [], "source": [ "class Padawan(Jedi):\n", " def __init__(self, name):\n", " self.name = name" ] }, { "cell_type": "code", "execution_count": 288, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 288, "metadata": {}, "output_type": "execute_result" } ], "source": [ "issubclass(Padawan, Jedi)" ] }, { "cell_type": "code", "execution_count": 289, "metadata": {}, "outputs": [], "source": [ "p = Padawan('Joerg')" ] }, { "cell_type": "code", "execution_count": 290, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 290, "metadata": {}, "output_type": "execute_result" } ], "source": [ "isinstance(p, Padawan)" ] }, { "cell_type": "code", "execution_count": 291, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 291, "metadata": {}, "output_type": "execute_result" } ], "source": [ "isinstance(p, Jedi)" ] }, { "cell_type": "code", "execution_count": 292, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Joerg'" ] }, "execution_count": 292, "metadata": {}, "output_type": "execute_result" } ], "source": [ "p.name" ] }, { "cell_type": "code", "execution_count": 293, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 293, "metadata": {}, "output_type": "execute_result" } ], "source": [ "hasattr(p, 'name')" ] }, { "cell_type": "code", "execution_count": 294, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Joerg'" ] }, "execution_count": 294, "metadata": {}, "output_type": "execute_result" } ], "source": [ "getattr(p, 'name')" ] }, { "cell_type": "code", "execution_count": 295, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Joerg'" ] }, "execution_count": 295, "metadata": {}, "output_type": "execute_result" } ], "source": [ "p.__dict__.get('name')" ] }, { "cell_type": "code", "execution_count": 297, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 297, "metadata": {}, "output_type": "execute_result" } ], "source": [ "hasattr(Jedi, 'LightSaber')" ] }, { "cell_type": "code", "execution_count": 299, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 299, "metadata": {}, "output_type": "execute_result" } ], "source": [ "hasattr(Padawan, 'LightSaber')" ] }, { "cell_type": "code", "execution_count": 300, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 300, "metadata": {}, "output_type": "execute_result" } ], "source": [ "Padawan.LightSaber" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Exception Handling" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Order of ``except`` Clauses" ] }, { "cell_type": "code", "execution_count": 159, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "ArithmeticError\n" ] } ], "source": [ "try:\n", " 1/0\n", "except ArithmeticError:\n", " print('ArithmeticError')\n", "except ZeroDivisionError:\n", " print('ZeroDivisionError')" ] }, { "cell_type": "code", "execution_count": 160, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 160, "metadata": {}, "output_type": "execute_result" } ], "source": [ "issubclass(ZeroDivisionError, ArithmeticError)" ] }, { "cell_type": "code", "execution_count": 161, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "ZeroDivisionError\n" ] } ], "source": [ "try:\n", " 1/0\n", "except ZeroDivisionError:\n", " print('ZeroDivisionError')\n", "except ArithmeticError:\n", " print('ArithmeticError')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## ``else``" ] }, { "cell_type": "code", "execution_count": 162, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "hallo du suesser!\n", "puh, hardware intakt\n" ] } ], "source": [ "try:\n", " print('hallo du suesser!')\n", "except OSError as e:\n", " print('WAAAH hardware abgebrannt!', e)\n", "else:\n", " print('puh, hardware intakt')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## ``finally``" ] }, { "cell_type": "code", "execution_count": 169, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "hallo du suesser!\n", "puh, hardware intakt\n", "wurscht, vorbei is\n" ] } ], "source": [ "try:\n", " print('hallo du suesser!')\n", "except OSError as e:\n", " print('WAAAH hardware abgebrannt!', e)\n", "else:\n", " print('puh, hardware intakt') # only if no exception\n", "finally:\n", " print('wurscht, vorbei is') # in any case" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# ``lambda``" ] }, { "cell_type": "code", "execution_count": 213, "metadata": {}, "outputs": [], "source": [ "def f(x):\n", " if x > 1:\n", " return 1\n", " else:\n", " return 0\n" ] }, { "cell_type": "code", "execution_count": 208, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 208, "metadata": {}, "output_type": "execute_result" } ], "source": [ "f(3)" ] }, { "cell_type": "code", "execution_count": 209, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0" ] }, "execution_count": 209, "metadata": {}, "output_type": "execute_result" } ], "source": [ "f(1)" ] }, { "cell_type": "code", "execution_count": 214, "metadata": {}, "outputs": [], "source": [ "f = lambda x: 1 if x>1 else 0" ] }, { "cell_type": "code", "execution_count": 212, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0" ] }, "execution_count": 212, "metadata": {}, "output_type": "execute_result" } ], "source": [ "f(1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# ``map()``, ``filter()``" ] }, { "cell_type": "code", "execution_count": 215, "metadata": {}, "outputs": [], "source": [ "def square(num):\n", " return num**2" ] }, { "cell_type": "code", "execution_count": 216, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "4\n", "1\n", "25\n", "9\n", "36\n" ] } ], "source": [ "l = [2, 1, 5, 3, 6]\n", "for element in map(square, l):\n", " print(element)" ] }, { "cell_type": "code", "execution_count": 217, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "map" ] }, "execution_count": 217, "metadata": {}, "output_type": "execute_result" } ], "source": [ "m = map(square, l)\n", "type(m)" ] }, { "cell_type": "code", "execution_count": 218, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "4\n", "1\n", "25\n", "9\n", "36\n" ] } ], "source": [ "for element in map(lambda num: num**2, l):\n", " print(element)" ] }, { "cell_type": "code", "execution_count": 219, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[2, 1, 5, 3, 6]" ] }, "execution_count": 219, "metadata": {}, "output_type": "execute_result" } ], "source": [ "l" ] }, { "cell_type": "code", "execution_count": 222, "metadata": {}, "outputs": [], "source": [ "def is_even(num):\n", " if num%2 == 0:\n", " return True\n", " return False" ] }, { "cell_type": "code", "execution_count": 223, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2\n", "6\n" ] } ], "source": [ "for element in filter(is_even, l):\n", " print(element)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Generators, Iteration Protocol" ] }, { "cell_type": "code", "execution_count": 224, "metadata": {}, "outputs": [], "source": [ "r = range(3)" ] }, { "cell_type": "code", "execution_count": 226, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0\n", "1\n", "2\n" ] } ], "source": [ "for element in r:\n", " print(element)" ] }, { "cell_type": "code", "execution_count": 227, "metadata": {}, "outputs": [], "source": [ "r = range(3)" ] }, { "cell_type": "code", "execution_count": 228, "metadata": {}, "outputs": [], "source": [ "it = iter(r)" ] }, { "cell_type": "code", "execution_count": 229, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0" ] }, "execution_count": 229, "metadata": {}, "output_type": "execute_result" } ], "source": [ "next(it)" ] }, { "cell_type": "code", "execution_count": 230, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 230, "metadata": {}, "output_type": "execute_result" } ], "source": [ "next(it)" ] }, { "cell_type": "code", "execution_count": 231, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "2" ] }, "execution_count": 231, "metadata": {}, "output_type": "execute_result" } ], "source": [ "next(it)" ] }, { "cell_type": "code", "execution_count": 233, "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": 234, "metadata": {}, "outputs": [], "source": [ "def my_range(limit):\n", " i = 0\n", " while i < limit:\n", " yield i\n", " i += 1" ] }, { "cell_type": "code", "execution_count": 235, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0\n", "1\n", "2\n" ] } ], "source": [ "for element in my_range(3):\n", " print(element)" ] }, { "cell_type": "code", "execution_count": 236, "metadata": {}, "outputs": [], "source": [ "r = my_range(3)" ] }, { "cell_type": "code", "execution_count": 238, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "generator" ] }, "execution_count": 238, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(r)" ] }, { "cell_type": "code", "execution_count": 241, "metadata": {}, "outputs": [], "source": [ "it = iter(r)" ] }, { "cell_type": "code", "execution_count": 242, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0" ] }, "execution_count": 242, "metadata": {}, "output_type": "execute_result" } ], "source": [ "next(it)" ] }, { "cell_type": "code", "execution_count": 243, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 243, "metadata": {}, "output_type": "execute_result" } ], "source": [ "next(it)" ] }, { "cell_type": "code", "execution_count": 244, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "2" ] }, "execution_count": 244, "metadata": {}, "output_type": "execute_result" } ], "source": [ "next(it)" ] }, { "cell_type": "code", "execution_count": 246, "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": "markdown", "metadata": {}, "source": [ "# Class Variables (as Opposed to Instance Variables)" ] }, { "cell_type": "code", "execution_count": 257, "metadata": {}, "outputs": [], "source": [ "class Blah:\n", " instances = []\n", " \n", " def __init__(self, value):\n", " Blah.instances.append(self)\n", " self.value = value" ] }, { "cell_type": "code", "execution_count": 258, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[]" ] }, "execution_count": 258, "metadata": {}, "output_type": "execute_result" } ], "source": [ "Blah.instances" ] }, { "cell_type": "code", "execution_count": 259, "metadata": {}, "outputs": [], "source": [ "b = Blah(42)" ] }, { "cell_type": "code", "execution_count": 260, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[<__main__.Blah at 0x7fac81f52df0>]" ] }, "execution_count": 260, "metadata": {}, "output_type": "execute_result" } ], "source": [ "b.instances" ] }, { "cell_type": "code", "execution_count": 261, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "42" ] }, "execution_count": 261, "metadata": {}, "output_type": "execute_result" } ], "source": [ "b.value" ] }, { "cell_type": "code", "execution_count": 262, "metadata": {}, "outputs": [], "source": [ "c = Blah(23)" ] }, { "cell_type": "code", "execution_count": 263, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[<__main__.Blah at 0x7fac81f52df0>, <__main__.Blah at 0x7fac81cb5700>]" ] }, "execution_count": 263, "metadata": {}, "output_type": "execute_result" } ], "source": [ "Blah.instances" ] }, { "cell_type": "code", "execution_count": 253, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "" ] }, "execution_count": 253, "metadata": {}, "output_type": "execute_result" } ], "source": [ "Blah.__init__" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Raw Strings" ] }, { "cell_type": "code", "execution_count": 264, "metadata": {}, "outputs": [], "source": [ "s = 'C:\\Progamme\\noch ein programm\\tumpfbacke'" ] }, { "cell_type": "code", "execution_count": 265, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "C:\\Progamme\n", "och ein programm\tumpfbacke\n" ] } ], "source": [ "print(s)" ] }, { "cell_type": "code", "execution_count": 266, "metadata": {}, "outputs": [], "source": [ "s = 'C:\\\\Progamme\\\\noch ein programm\\\\tumpfbacke'" ] }, { "cell_type": "code", "execution_count": 267, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "C:\\Progamme\\noch ein programm\\tumpfbacke\n" ] } ], "source": [ "print(s)" ] }, { "cell_type": "code", "execution_count": 268, "metadata": {}, "outputs": [], "source": [ "s = r'C:\\Progamme\\noch ein programm\\tumpfbacke'" ] }, { "cell_type": "code", "execution_count": 269, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "C:\\Progamme\\noch ein programm\\tumpfbacke\n" ] } ], "source": [ "print(s)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# File IO" ] }, { "cell_type": "code", "execution_count": 270, "metadata": {}, "outputs": [], "source": [ "f = open('file.txt', 'rt') # r and t are default anyway" ] }, { "cell_type": "code", "execution_count": 271, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "zeile 1\n", "\n", "zeile 2\n", "\n", "zeile 3\n", "\n", "zeile 4\n", "\n" ] } ], "source": [ "for line in f:\n", " print(line)" ] }, { "cell_type": "code", "execution_count": 273, "metadata": {}, "outputs": [], "source": [ "f = open('file.txt', 'rt') # r and t are default anyway" ] }, { "cell_type": "code", "execution_count": 274, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "zeile 1\n", "zeile 2\n", "zeile 3\n", "zeile 4\n" ] } ], "source": [ "for line in f:\n", " print(line, end='')" ] }, { "cell_type": "code", "execution_count": 278, "metadata": {}, "outputs": [], "source": [ "f = open('file.txt', 'rt') # r and t are default anyway" ] }, { "cell_type": "code", "execution_count": 279, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'zeile 1\\nzeile 2\\nzeile 3\\nzeile 4\\n'" ] }, "execution_count": 279, "metadata": {}, "output_type": "execute_result" } ], "source": [ "wholefile = f.read()\n", "wholefile" ] }, { "cell_type": "code", "execution_count": 280, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "zeile 1\n", "zeile 2\n", "zeile 3\n", "zeile 4\n", "\n" ] } ], "source": [ "print(wholefile)" ] }, { "cell_type": "code", "execution_count": 281, "metadata": {}, "outputs": [], "source": [ "f = open('file.txt', 'rt') # r and t are default anyway" ] }, { "cell_type": "code", "execution_count": 282, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "z\n", "e\n", "i\n", "l\n", "e\n", " \n", "1\n", "\n", "\n", "z\n", "e\n", "i\n", "l\n", "e\n", " \n", "2\n", "\n", "\n", "z\n", "e\n", "i\n", "l\n", "e\n", " \n", "3\n", "\n", "\n", "z\n", "e\n", "i\n", "l\n", "e\n", " \n", "4\n", "\n", "\n" ] } ], "source": [ "wholefile = f.read()\n", "for c in wholefile:\n", " print(c)" ] }, { "cell_type": "code", "execution_count": 284, "metadata": {}, "outputs": [], "source": [ "f = open('file.txt', 'rt') # r and t are default anyway" ] }, { "cell_type": "code", "execution_count": 285, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "zeile 1\n", "zeile 2\n", "zeile 3\n", "zeile 4\n" ] } ], "source": [ "wholefile = f.read()\n", "for c in wholefile:\n", " print(c, end='')" ] } ], "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 }