Python (2022-11-16 - 2022-11-18)

Object Oriented

[1]:
print('Hello World')
Hello World
[2]:
a = 42
[3]:
print(type(a))
<class 'int'>
[4]:
import sys
sys.getsizeof(a)
[4]:
28
[5]:
print(type(print))
<class 'builtin_function_or_method'>
[6]:
print(type(type))
<class 'type'>
[7]:
print.__doc__
[7]:
"print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n\nPrints the values to a stream, or to sys.stdout by default.\nOptional keyword arguments:\nfile:  a file-like object (stream); defaults to the current sys.stdout.\nsep:   string inserted between values, default a space.\nend:   string appended after the last value, default a newline.\nflush: whether to forcibly flush the stream."
[8]:
help(print)
Help on built-in function print in module builtins:

print(...)
    print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file:  a file-like object (stream); defaults to the current sys.stdout.
    sep:   string inserted between values, default a space.
    end:   string appended after the last value, default a newline.
    flush: whether to forcibly flush the stream.

[9]:
class Person:
    '''Some pointless and repetitive implementation of
    yet another Person class (for didactical purposes only)'''
    def __init__(self, firstname, lastname):
        self.firstname = firstname
        self.lastname = lastname
    def fullname(self):
        return self.firstname + ' ' + self.lastname
[10]:
joerg = Person('Joerg', 'Faschingbauer')
[11]:
type(joerg)
[11]:
__main__.Person
[12]:
joerg.firstname
[12]:
'Joerg'
[13]:
joerg.fullname()
[13]:
'Joerg Faschingbauer'
[14]:
Person
[14]:
__main__.Person
[15]:
type(Person)
[15]:
type
[16]:
Person.__name__
[16]:
'Person'
[17]:
dir(Person)
[17]:
['__class__',
 '__delattr__',
 '__dict__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__gt__',
 '__hash__',
 '__init__',
 '__init_subclass__',
 '__le__',
 '__lt__',
 '__module__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 '__weakref__',
 'fullname']
[18]:
Person.__doc__
[18]:
'Some pointless and repetitive implementation of\n    yet another Person class (for didactical purposes only)'
[19]:
help(Person)
Help on class Person in module __main__:

class Person(builtins.object)
 |  Person(firstname, lastname)
 |
 |  Some pointless and repetitive implementation of
 |  yet another Person class (for didactical purposes only)
 |
 |  Methods defined here:
 |
 |  __init__(self, firstname, lastname)
 |      Initialize self.  See help(type(self)) for accurate signature.
 |
 |  fullname(self)
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |
 |  __dict__
 |      dictionary for instance variables (if defined)
 |
 |  __weakref__
 |      list of weak references to the object (if defined)

Integers

[20]:
i = 666
[21]:
type(i)
[21]:
int
[22]:
i = 2**64 - 1
[23]:
bin(i)
[23]:
'0b1111111111111111111111111111111111111111111111111111111111111111'
[24]:
len(bin(i))
[24]:
66
[25]:
i += 1
[26]:
i
[26]:
18446744073709551616
[27]:
bin(i)
[27]:
'0b10000000000000000000000000000000000000000000000000000000000000000'
[28]:
len(bin(i))
[28]:
67
[29]:
2**1000
[29]:
10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376
[30]:
a = 42
[31]:
a
[31]:
42
[32]:
a == 42
[32]:
True
[33]:
if a == 42:
    print('hurra')
hurra

Strings

[34]:
s = 'abc'
s
[34]:
'abc'
[35]:
s = "abc"
s
[35]:
'abc'
[36]:
s = 'ab"c'
s
[36]:
'ab"c'
[37]:
s = "ab'c"
s
[37]:
"ab'c"
[38]:
s = "ab\"'c"
s
[38]:
'ab"\'c'
[39]:
s = 'ab"\'c'
s
[39]:
'ab"\'c'
[40]:
s = """
erste zeile
zweite zeile
"""
s
[40]:
'\nerste zeile\nzweite zeile\n'

Datatype Conversions

[41]:
round(12.9)
[41]:
13
[42]:
round(12.1)
[42]:
12
[43]:
try:
    int('abc')
except ValueError as e:
    print(e)
invalid literal for int() with base 10: 'abc'
[44]:
int('abc', 16)
[44]:
2748
[45]:
try:
    int('abc')
except BaseException as e:
    print(e)
invalid literal for int() with base 10: 'abc'
[46]:
try:
    int('abc')
except Exception as e:
    print(e)
invalid literal for int() with base 10: 'abc'

Lists and Tuples

[47]:
l = [1,2,'drei']
l
[47]:
[1, 2, 'drei']
[48]:
len(l)
[48]:
3
[49]:
l.append(4.0)
l
[49]:
[1, 2, 'drei', 4.0]
[50]:
andere_liste = [5, 6, 7]
[51]:
neue_liste = l + andere_liste
neue_liste
[51]:
[1, 2, 'drei', 4.0, 5, 6, 7]
[52]:
l
[52]:
[1, 2, 'drei', 4.0]
[53]:
andere_liste
[53]:
[5, 6, 7]
[54]:
l += andere_liste
l
[54]:
[1, 2, 'drei', 4.0, 5, 6, 7]
[55]:
l.append([8,9,10])
l
[55]:
[1, 2, 'drei', 4.0, 5, 6, 7, [8, 9, 10]]
[56]:
l.extend([11,12,13,14])
l
[56]:
[1, 2, 'drei', 4.0, 5, 6, 7, [8, 9, 10], 11, 12, 13, 14]
[57]:
l[2]
[57]:
'drei'
[58]:
del l[2]
[59]:
l
[59]:
[1, 2, 4.0, 5, 6, 7, [8, 9, 10], 11, 12, 13, 14]
[60]:
5 in l
[60]:
True
[61]:
14 in l
[61]:
True
[62]:
666 in l
[62]:
False
[63]:
t = (1,2,3)
t
[63]:
(1, 2, 3)
[64]:
t[2]
[64]:
3
[65]:
len(t)
[65]:
3
[66]:
try:
    t.append(4)
except AttributeError as e:
    print(e)
'tuple' object has no attribute 'append'

Dictionary

[67]:
d = {1:'one', 2:'two'}
[68]:
1 in d
[68]:
True
[69]:
d[1]
[69]:
'one'
[70]:
try:
    d[3]
except KeyError as e:
    print(e)
3
[71]:
d[3] = 'drei'
d
[71]:
{1: 'one', 2: 'two', 3: 'drei'}
[72]:
del d[1]
d
[72]:
{2: 'two', 3: 'drei'}
[73]:
for elem in d:
    print(elem)
2
3
[74]:
for elem in d.keys():
    print(elem)
2
3
[75]:
for elem in d.values():
    print(elem)
two
drei
[76]:
for elem in d.items():
    print(elem)
(2, 'two')
(3, 'drei')
[77]:
for key, value in d.items():
    print(key, value)
2 two
3 drei

Set

[78]:
s = {1,2,3}
s
[78]:
{1, 2, 3}
[79]:
1 in s
[79]:
True
[80]:
666 in s
[80]:
False
[81]:
for elem in s:
    print(elem)
1
2
3
[82]:
s.add('vier')
s
[82]:
{1, 2, 3, 'vier'}
[83]:
s.remove(3)

for, and Iteration, and Generators

[84]:
l = [1,2,3,4]
for elem in l:
    print(elem)
1
2
3
4
[85]:
for elem in range(1,5):
    print(elem)
1
2
3
4
[86]:
d = {'one': 1, 'two': 2}
for elem in d:
    print(elem)
one
two
[87]:
for elem in d.keys():
    print(elem)
one
two
[88]:
for elem in d.values():
    print(elem)
1
2
[89]:
for elem in d.items():
    print(elem)
('one', 1)
('two', 2)
[90]:
for elem in d.items():
    key = elem[0]
    value = elem[1]
    print(f'Key={key}, Value={value}')
Key=one, Value=1
Key=two, Value=2
[91]:
f = open('/etc/passwd')
for line in f:
    print(line)
root:x:0:0:root:/root:/bin/bash

bin:x:1:1:bin:/bin:/sbin/nologin

daemon:x:2:2:daemon:/sbin:/sbin/nologin

adm:x:3:4:adm:/var/adm:/sbin/nologin

lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin

sync:x:5:0:sync:/sbin:/bin/sync

shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown

halt:x:7:0:halt:/sbin:/sbin/halt

mail:x:8:12:mail:/var/spool/mail:/sbin/nologin

operator:x:11:0:operator:/root:/sbin/nologin

games:x:12:100:games:/usr/games:/sbin/nologin

ftp:x:14:50:FTP User:/var/ftp:/sbin/nologin

nobody:x:65534:65534:Kernel Overflow User:/:/sbin/nologin

dbus:x:81:81:System message bus:/:/sbin/nologin

apache:x:48:48:Apache:/usr/share/httpd:/sbin/nologin

tss:x:59:59:Account used for TPM access:/dev/null:/sbin/nologin

systemd-network:x:192:192:systemd Network Management:/:/usr/sbin/nologin

systemd-oom:x:999:999:systemd Userspace OOM Killer:/:/usr/sbin/nologin

systemd-resolve:x:193:193:systemd Resolver:/:/usr/sbin/nologin

qemu:x:107:107:qemu user:/:/sbin/nologin

polkitd:x:998:997:User for polkitd:/:/sbin/nologin

avahi:x:70:70:Avahi mDNS/DNS-SD Stack:/var/run/avahi-daemon:/sbin/nologin

unbound:x:997:995:Unbound DNS resolver:/etc/unbound:/sbin/nologin

nm-openconnect:x:996:994:NetworkManager user for OpenConnect:/:/sbin/nologin

geoclue:x:995:993:User for geoclue:/var/lib/geoclue:/sbin/nologin

usbmuxd:x:113:113:usbmuxd user:/:/sbin/nologin

gluster:x:994:992:GlusterFS daemons:/run/gluster:/sbin/nologin

rtkit:x:172:172:RealtimeKit:/proc:/sbin/nologin

chrony:x:993:990::/var/lib/chrony:/sbin/nologin

saslauth:x:992:76:Saslauthd user:/run/saslauthd:/sbin/nologin

dnsmasq:x:991:989:Dnsmasq DHCP and DNS server:/var/lib/dnsmasq:/sbin/nologin

rpc:x:32:32:Rpcbind Daemon:/var/lib/rpcbind:/sbin/nologin

colord:x:990:988:User for colord:/var/lib/colord:/sbin/nologin

rpcuser:x:29:29:RPC Service User:/var/lib/nfs:/sbin/nologin

openvpn:x:989:987:OpenVPN:/etc/openvpn:/sbin/nologin

nm-openvpn:x:988:986:Default user for running openvpn spawned by NetworkManager:/:/sbin/nologin

pipewire:x:987:985:PipeWire System Daemon:/var/run/pipewire:/sbin/nologin

abrt:x:173:173::/etc/abrt:/sbin/nologin

flatpak:x:986:983:User for flatpak system helper:/:/sbin/nologin

gdm:x:42:42:GNOME Display Manager:/var/lib/gdm:/sbin/nologin

gnome-initial-setup:x:985:982::/run/gnome-initial-setup/:/sbin/nologin

vboxadd:x:984:1::/var/run/vboxadd:/sbin/nologin

sshd:x:74:74:Privilege-separated SSH:/usr/share/empty.sshd:/sbin/nologin

tcpdump:x:72:72::/:/sbin/nologin

jfasch:x:1000:1000:Joerg Faschingbauer:/home/jfasch:/bin/bash

systemd-coredump:x:978:978:systemd Core Dumper:/:/usr/sbin/nologin

systemd-timesync:x:977:977:systemd Time Synchronization:/:/usr/sbin/nologin

mosquitto:x:976:976:Mosquitto Broker:/etc/mosquitto:/sbin/nologin

[92]:
for elem in range(3):
    print(elem)
0
1
2
[93]:
r = range(3)
type(r)
[93]:
range
[94]:
r = range(10**1000)
r
[94]:
range(0, 10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000)
[95]:
r = range(3)
r
[95]:
range(0, 3)
[96]:
for elem in r:
    print(elem)
0
1
2

Iterator Protocol

[97]:
r = range(3)
[98]:
it = iter(r)
[99]:
type(it)
[99]:
range_iterator
[100]:
next(it)
[100]:
0
[101]:
next(it)
[101]:
1
[102]:
next(it)
[102]:
2
[103]:
try:
    next(it)
except StopIteration:
    pass

enumerate()

[104]:
names = ['Joerg', 'Caro', 'Johanna', 'Philipp']
for name in names:
    print(name)
Joerg
Caro
Johanna
Philipp
[105]:
for i in range(len(names)):
    print(i, names[i])
0 Joerg
1 Caro
2 Johanna
3 Philipp
[106]:
i = 0
while i < len(names):
    print(i, names[i])
    i += 1
0 Joerg
1 Caro
2 Johanna
3 Philipp
[107]:
for elem in enumerate(names):
    print(elem)
(0, 'Joerg')
(1, 'Caro')
(2, 'Johanna')
(3, 'Philipp')
[108]:
for i, name in enumerate(names):
    print(i, name)
0 Joerg
1 Caro
2 Johanna
3 Philipp

Lists, Dictionaries, Generators, Constructors

[109]:
for i in range(3):
    print(i)
0
1
2
[110]:
l = []
for i in range(3):
    l.append(i)
l
[110]:
[0, 1, 2]
[111]:
list(range(3))
[111]:
[0, 1, 2]
[112]:
for i in 'abc':
    print(i)
a
b
c
[113]:
list('abc')
[113]:
['a', 'b', 'c']
[114]:
d = {'one': 1, 'two': 2}
for elem in d:
    print(elem)
one
two
[115]:
list(d)
[115]:
['one', 'two']
[116]:
l = [('one', 1), ('two', 2)]
for k, v in l:
    print(k, v)
one 1
two 2
[117]:
dict(l)
[117]:
{'one': 1, 'two': 2}

Slicing

[118]:
text = 'Hello World'
text[-1:-5]
[118]:
''
[119]:
for i in range(0,7,2):
    print(i)
0
2
4
6

References, (Im)mutability

[120]:
a = 42
b = a
[121]:
id(a)
[121]:
140323934455312
[122]:
id(b)
[122]:
140323934455312
[123]:
a += 1
a
[123]:
43
[124]:
b
[124]:
42
[125]:
id(a)
[125]:
140323934455344
[126]:
a += 1
id(a)
[126]:
140323934455376

And Lists? Mutable!

[127]:
l1 = [1,2,3]
l2 = l1
l2
[127]:
[1, 2, 3]
[128]:
l1.append(4)
l1
[128]:
[1, 2, 3, 4]
[129]:
l2
[129]:
[1, 2, 3, 4]

Tuples?

[130]:
t1 = (1,2,3)
t2 = t1
[131]:
id(t1)
[131]:
140323852147712
[132]:
id(t2)
[132]:
140323852147712
[133]:
try:
    t1.append(4)
except AttributeError as e:
    print(e)
'tuple' object has no attribute 'append'
[134]:
try:
    del t[1]
except TypeError as e:
    print(e)
'tuple' object doesn't support item deletion

Strings

[135]:
s1 = 'abc'
s2 = s1
id(s1)
[135]:
140323933649904
[136]:
id(s2)
[136]:
140323933649904
[137]:
s1 += 'def'
id(s1)
[137]:
140323833601584
[138]:
s2
[138]:
'abc'

set

[139]:
s1 = {1,2,3}
s2 = s1
id(s1) == id(s2)
[139]:
True
[140]:
s1.add(4)
s1
[140]:
{1, 2, 3, 4}
[141]:
s2
[141]:
{1, 2, 3, 4}
[142]:
s1 = frozenset((1,2,3))
s1
[142]:
frozenset({1, 2, 3})
[143]:
try:
    s1.add(4)
except AttributeError as e:
    print(e)
'frozenset' object has no attribute 'add'
[144]:
s2 = set(s1)
s2.add(4)

Functions

[145]:
a, b = [1,2]
a
[145]:
1
[146]:
b
[146]:
2
[147]:
def f():
    return 1, 2
i, j = f()
[148]:
i
[148]:
1
[149]:
j
[149]:
2
[150]:
def f():
    return (1,2)
(i, j) = f()
[151]:
def maximum(a, b):
    if a < b:
        return b
    return a
[152]:
maximum
[152]:
<function __main__.maximum(a, b)>
[153]:
type(maximum)
[153]:
function
[154]:
a = maximum
a(1,2)
[154]:
2
[155]:
maximum.__name__
[155]:
'maximum'
[156]:
dir(maximum)
[156]:
['__annotations__',
 '__builtins__',
 '__call__',
 '__class__',
 '__closure__',
 '__code__',
 '__defaults__',
 '__delattr__',
 '__dict__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__get__',
 '__getattribute__',
 '__globals__',
 '__gt__',
 '__hash__',
 '__init__',
 '__init_subclass__',
 '__kwdefaults__',
 '__le__',
 '__lt__',
 '__module__',
 '__name__',
 '__ne__',
 '__new__',
 '__qualname__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__']
[157]:
def greet(who, phrase='Grüß Gott'):
    print(phrase, who)
[158]:
greet('Jörg')
Grüß Gott Jörg
[159]:
greet('Jörg', 'Seas')
Seas Jörg
[160]:
def f(x=[]):
    print(x)
[161]:
f()
[]
[162]:
f([1,2,3])
[1, 2, 3]
[163]:
def f(x=[]):
    x.append(42)
    print(x)
[164]:
f()
[42]
[165]:
f()
[42, 42]
[166]:
f.__defaults__
[166]:
([42, 42],)

Strings

[167]:
s = 'abc'
s
[167]:
'abc'
[168]:
s = "abc"
s
[168]:
'abc'
[169]:
s = 'abc"def'
s
[169]:
'abc"def'
[170]:
s = "abc'def"
s
[170]:
"abc'def"
[171]:
s = 'abc"\'def'
s
[171]:
'abc"\'def'
[172]:
print(s)
abc"'def
[173]:
s = 'erste zeile\nzweite zeile'
s
[173]:
'erste zeile\nzweite zeile'
[174]:
print(s)
erste zeile
zweite zeile
[175]:
s = 'abc\tdef'
print(s)
abc     def
[176]:
doze_path = 'C:\Programme\nocheinprogramm'
print(doze_path)
C:\Programme
ocheinprogramm
[177]:
doze_path = 'C:\\Programme\\nocheinprogramm'
print(doze_path)
C:\Programme\nocheinprogramm
[178]:
doze_path = r'C:\Programme\nocheinprogramm'
print(doze_path)
C:\Programme\nocheinprogramm

Regular Expressions

[179]:
line = '     dfghgfdfghj.  123   .   '
[180]:
line = 'jhghgh   .123.   '
[181]:
import re
[182]:
matchstr = r'^\s*([a-z]+)\s*\.\s*(\d+)\s*\.\s*$'
[183]:
compiled_match = re.compile(matchstr)
[184]:
match = compiled_match.search('jhghgh   .123.   ')
[185]:
match.group(1)
[185]:
'jhghgh'
[186]:
int(match.group(2))
[186]:
123

Miscellaneous String Methods

[187]:
s = '123'
s.isdigit()
[187]:
True
[188]:
s = '    \t   \r\n'
s.isspace()
[188]:
True
[189]:
s = 'abc'
s.isalpha()
[189]:
True
[190]:
s.islower()
[190]:
True
[191]:
s.upper()
[191]:
'ABC'
[192]:
s = s.upper()
[193]:
s
[193]:
'ABC'
[194]:
s.lower()
[194]:
'abc'
[195]:
s = 'a'
s.isidentifier()
[195]:
True
[196]:
s = '_a'
s.isidentifier()
[196]:
True
[197]:
s = 'abc'
s.capitalize()
[197]:
'Abc'
[198]:
s.center(50)
[198]:
'                       abc                        '
[199]:
s = 'mississippi'
s.count('ss')
[199]:
2
[200]:
s = 'ein.csv'
s.endswith('.csv')
[200]:
True
[201]:
s = '\tprint("hallo")'
s.expandtabs(4)
[201]:
'    print("hallo")'
[202]:
s = 'mississippi'
s.find('ss')
[202]:
2
[203]:
num_ss = 0
pos = 0
while True:
    pos = s.find('ss', pos)
    if pos == -1:
        break
    num_ss += 1
    pos += 1
print('ss gefunden:', num_ss)
ss gefunden: 2
[204]:
s
[204]:
'mississippi'
[205]:
s.index('ss')
[205]:
2
[206]:
try:
    s.index('xyz')
except ValueError as e:
    print(e)
substring not found
[207]:
s = '   abc    '
[208]:
s.strip()
[208]:
'abc'
[209]:
s.lstrip()
[209]:
'abc    '
[210]:
s.rstrip()
[210]:
'   abc'
[211]:
s = 'line\n'
[212]:
s.rstrip('\n')
[212]:
'line'
[213]:
items = ['Joerg', 'Caro', 'Philipp', 'Johanna', 'Isi']
','.join(items)
[213]:
'Joerg,Caro,Philipp,Johanna,Isi'
[214]:
line = ','.join(items)
line
[214]:
'Joerg,Caro,Philipp,Johanna,Isi'
[215]:
line.split(',')
[215]:
['Joerg', 'Caro', 'Philipp', 'Johanna', 'Isi']
[216]:
line = '     dfghgfdfghj.  123   .   '
[217]:
items = line.split('.')
items
[217]:
['     dfghgfdfghj', '  123   ', '   ']
[218]:
strippeditems = []
for item in items:
    strippeditems.append(item.strip())
strippeditems
[218]:
['dfghgfdfghj', '123', '']
[219]:
strippeditems = [item.strip() for item in items]
items
[219]:
['     dfghgfdfghj', '  123   ', '   ']

More About Lists

[220]:
l =  [3, 2, 5]
[221]:
l.append(5)
[222]:
l
[222]:
[3, 2, 5, 5]
[223]:
l1 = ['noch', 'was']
[224]:
l.extend(l1)
l
[224]:
[3, 2, 5, 5, 'noch', 'was']
[225]:
l.append(l1)
[226]:
l
[226]:
[3, 2, 5, 5, 'noch', 'was', ['noch', 'was']]
[227]:
try:
    l.sort()
except TypeError as e:
    print(e)
'<' not supported between instances of 'str' and 'int'
[228]:
l = [4, 1, 6, 666, 42]
[229]:
l.sort()
[230]:
l
[230]:
[1, 4, 6, 42, 666]
[231]:
l = [4, 1, 6, 666, 42]
[232]:
sorted(l)
[232]:
[1, 4, 6, 42, 666]
[233]:
l.reverse()
[234]:
l
[234]:
[42, 666, 6, 1, 4]
[235]:
list(reversed(l))
[235]:
[4, 1, 6, 666, 42]
[236]:
666 in l
[236]:
True

More About Dictionaries

[237]:
d = {}
[238]:
type(d)
[238]:
dict
[239]:
d = dict()
[240]:
d
[240]:
{}
[241]:
d['one'] = 1
d['two'] = 2
[242]:
d
[242]:
{'one': 1, 'two': 2}
[243]:
d = {'one': 1, 'two': 2}
[244]:
d['one']
[244]:
1
[245]:
d['three'] = 3
[246]:
d['three']
[246]:
3
[247]:
try:
    d['four']
except KeyError as e:
    print(e)
'four'
[248]:
d.get('three')
[248]:
3
[249]:
value = d.get('four')
print(value)
None
[250]:
value = d.get('four')
if value is None:
    d['four'] = 4
else:
    print(value)
[251]:
d
[251]:
{'one': 1, 'two': 2, 'three': 3, 'four': 4}
[252]:
value = d.get('five', 5)
value
[252]:
5
[253]:
d
[253]:
{'one': 1, 'two': 2, 'three': 3, 'four': 4}
[254]:
value = d.setdefault('five', 5)
value
[254]:
5
[255]:
d
[255]:
{'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5}
[256]:
other_d = {'hundred': 100, 'thousand': 1000}
[257]:
d.update(other_d)
[258]:
d
[258]:
{'one': 1,
 'two': 2,
 'three': 3,
 'four': 4,
 'five': 5,
 'hundred': 100,
 'thousand': 1000}
[259]:
yet_another_d = {'thousand': 1, 'one': 1000}
[260]:
d.update(yet_another_d)
d
[260]:
{'one': 1000,
 'two': 2,
 'three': 3,
 'four': 4,
 'five': 5,
 'hundred': 100,
 'thousand': 1}

More About Sets

[261]:
s = set()
[262]:
s
[262]:
set()
[263]:
s = {1, 2, 3}
[264]:
3 in s
[264]:
True
[265]:
3 not in s
[265]:
False
[266]:
4 not in s
[266]:
True
[267]:
s.add(4)
[268]:
4 in s
[268]:
True
[269]:
s.remove(2)
[270]:
2 in s
[270]:
False
[271]:
s == s
[271]:
True
[272]:
s
[272]:
{1, 3, 4}
[273]:
s1 = {1,2,3}
s2 = {3,1,2}
s1 == s2
[273]:
True
[274]:
s3 = {1,2,3,4}
[275]:
s1 == s3
[275]:
False
[276]:
s1 < s3
[276]:
True
[277]:
s3 > s1
[277]:
True
[278]:
s4 = {1000, 2000}
[279]:
s1.isdisjoint(s4)
[279]:
True

Comprehensions (List, Dictionary, Set)

List

[280]:
squares = []
for num in range(5):
    squares.append(num**2)
[281]:
for sq in squares:
    print(sq)
0
1
4
9
16
[282]:
for sq in [num**2 for num in range(5)]:
    print(sq)
0
1
4
9
16
[283]:
for sq in [num**2 for num in range(10) if num%2==0]:
    print(sq)
0
4
16
36
64

Dictionary

[284]:
dict([('one', 1), ('two', 2)])
[284]:
{'one': 1, 'two': 2}
[285]:
squares = {}
for num in range(5):
    squares[num] = num**2
[286]:
squares
[286]:
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
[287]:
squares = {num: num**2 for num in range(5)}
squares
[287]:
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

Set

[288]:
squares = set()
for num in range(5):
    squares.add(num**2)
squares
[288]:
{0, 1, 4, 9, 16}
[289]:
squares = {num**2 for num in range(5)}
squares
[289]:
{0, 1, 4, 9, 16}

Generator Expressions

[290]:
def squares(seq):
    squares = []
    for num in range(5):
        squares.append(num**2)
    return squares
[291]:
for sq in squares(range(5)):
    print(sq)
0
1
4
9
16
[292]:
def squares(seq):
    for num in range(5):
        yield num**2
[293]:
for sq in squares(range(5)):
    print(sq)
0
1
4
9
16
[294]:
for sq in [num**2 for num in range(5)]:
    print(sq)
0
1
4
9
16
[295]:
for sq in (num**2 for num in range(5)):
    print(sq)
0
1
4
9
16

eval and exec

[296]:
s = '42'
[298]:
int(s)     # BORING!
[298]:
42
[299]:
eval(s)
[299]:
42
[300]:
s = '[1,2,3]'
eval(s)
[300]:
[1, 2, 3]
[301]:
s = '"    ".strip()'
eval(s)
[301]:
''
[302]:
value = print('hallo')
value
hallo
[305]:
print(value)
None
[306]:
s = 'print("hallo")'
value = eval(s)
hallo
[307]:
print(value)
None
[311]:
s = '['
s += '1,'
s += '2,'
s += '"drei"]'
s
[311]:
'[1,2,"drei"]'
[312]:
eval(s)
[312]:
[1, 2, 'drei']
[314]:
s = 'for i in range(5): print(i)'
exec(s)
0
1
2
3
4
[315]:
s = '''
a = 666
print(a)
'''
exec(s)
666
[316]:
a
[316]:
666
[317]:
del a
[319]:
s
[319]:
'\na = 666\nprint(a)\n'
[320]:
context = {}
[323]:
exec(s, context)
666
[324]:
context
[324]:
{'__builtins__': {'__name__': 'builtins',
  '__doc__': "Built-in functions, exceptions, and other objects.\n\nNoteworthy: None is the `nil' object; Ellipsis represents `...' in slices.",
  '__package__': '',
  '__loader__': _frozen_importlib.BuiltinImporter,
  '__spec__': ModuleSpec(name='builtins', loader=<class '_frozen_importlib.BuiltinImporter'>, origin='built-in'),
  '__build_class__': <function __build_class__>,
  '__import__': <function __import__>,
  'abs': <function abs(x, /)>,
  'all': <function all(iterable, /)>,
  'any': <function any(iterable, /)>,
  'ascii': <function ascii(obj, /)>,
  'bin': <function bin(number, /)>,
  'breakpoint': <function breakpoint>,
  'callable': <function callable(obj, /)>,
  'chr': <function chr(i, /)>,
  'compile': <function compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1, *, _feature_version=-1)>,
  'delattr': <function delattr(obj, name, /)>,
  'dir': <function dir>,
  'divmod': <function divmod(x, y, /)>,
  'eval': <function eval(source, globals=None, locals=None, /)>,
  'exec': <function exec(source, globals=None, locals=None, /)>,
  'format': <function format(value, format_spec='', /)>,
  'getattr': <function getattr>,
  'globals': <function globals()>,
  'hasattr': <function hasattr(obj, name, /)>,
  'hash': <function hash(obj, /)>,
  'hex': <function hex(number, /)>,
  'id': <function id(obj, /)>,
  'input': <bound method Kernel.raw_input of <ipykernel.ipkernel.IPythonKernel object at 0x7f9fb16abcd0>>,
  'isinstance': <function isinstance(obj, class_or_tuple, /)>,
  'issubclass': <function issubclass(cls, class_or_tuple, /)>,
  'iter': <function iter>,
  'aiter': <function aiter(async_iterable, /)>,
  'len': <function len(obj, /)>,
  'locals': <function locals()>,
  'max': <function max>,
  'min': <function min>,
  'next': <function next>,
  'anext': <function anext>,
  'oct': <function oct(number, /)>,
  'ord': <function ord(c, /)>,
  'pow': <function pow(base, exp, mod=None)>,
  'print': <function print>,
  'repr': <function repr(obj, /)>,
  'round': <function round(number, ndigits=None)>,
  'setattr': <function setattr(obj, name, value, /)>,
  'sorted': <function sorted(iterable, /, *, key=None, reverse=False)>,
  'sum': <function sum(iterable, /, start=0)>,
  'vars': <function vars>,
  'None': None,
  'Ellipsis': Ellipsis,
  'NotImplemented': NotImplemented,
  'False': False,
  'True': True,
  'bool': bool,
  'memoryview': memoryview,
  'bytearray': bytearray,
  'bytes': bytes,
  'classmethod': classmethod,
  'complex': complex,
  'dict': dict,
  'enumerate': enumerate,
  'filter': filter,
  'float': float,
  'frozenset': frozenset,
  'property': property,
  'int': int,
  'list': list,
  'map': map,
  'object': object,
  'range': range,
  'reversed': reversed,
  'set': set,
  'slice': slice,
  'staticmethod': staticmethod,
  'str': str,
  'super': super,
  'tuple': tuple,
  'type': type,
  'zip': zip,
  '__debug__': True,
  'BaseException': BaseException,
  'Exception': Exception,
  'TypeError': TypeError,
  'StopAsyncIteration': StopAsyncIteration,
  'StopIteration': StopIteration,
  'GeneratorExit': GeneratorExit,
  'SystemExit': SystemExit,
  'KeyboardInterrupt': KeyboardInterrupt,
  'ImportError': ImportError,
  'ModuleNotFoundError': ModuleNotFoundError,
  'OSError': OSError,
  'EnvironmentError': OSError,
  'IOError': OSError,
  'EOFError': EOFError,
  'RuntimeError': RuntimeError,
  'RecursionError': RecursionError,
  'NotImplementedError': NotImplementedError,
  'NameError': NameError,
  'UnboundLocalError': UnboundLocalError,
  'AttributeError': AttributeError,
  'SyntaxError': SyntaxError,
  'IndentationError': IndentationError,
  'TabError': TabError,
  'LookupError': LookupError,
  'IndexError': IndexError,
  'KeyError': KeyError,
  'ValueError': ValueError,
  'UnicodeError': UnicodeError,
  'UnicodeEncodeError': UnicodeEncodeError,
  'UnicodeDecodeError': UnicodeDecodeError,
  'UnicodeTranslateError': UnicodeTranslateError,
  'AssertionError': AssertionError,
  'ArithmeticError': ArithmeticError,
  'FloatingPointError': FloatingPointError,
  'OverflowError': OverflowError,
  'ZeroDivisionError': ZeroDivisionError,
  'SystemError': SystemError,
  'ReferenceError': ReferenceError,
  'MemoryError': MemoryError,
  'BufferError': BufferError,
  'Warning': Warning,
  'UserWarning': UserWarning,
  'EncodingWarning': EncodingWarning,
  'DeprecationWarning': DeprecationWarning,
  'PendingDeprecationWarning': PendingDeprecationWarning,
  'SyntaxWarning': SyntaxWarning,
  'RuntimeWarning': RuntimeWarning,
  'FutureWarning': FutureWarning,
  'ImportWarning': ImportWarning,
  'UnicodeWarning': UnicodeWarning,
  'BytesWarning': BytesWarning,
  'ResourceWarning': ResourceWarning,
  'ConnectionError': ConnectionError,
  'BlockingIOError': BlockingIOError,
  'BrokenPipeError': BrokenPipeError,
  'ChildProcessError': ChildProcessError,
  'ConnectionAbortedError': ConnectionAbortedError,
  'ConnectionRefusedError': ConnectionRefusedError,
  'ConnectionResetError': ConnectionResetError,
  'FileExistsError': FileExistsError,
  'FileNotFoundError': FileNotFoundError,
  'IsADirectoryError': IsADirectoryError,
  'NotADirectoryError': NotADirectoryError,
  'InterruptedError': InterruptedError,
  'PermissionError': PermissionError,
  'ProcessLookupError': ProcessLookupError,
  'TimeoutError': TimeoutError,
  'open': <function io.open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)>,
  'copyright': Copyright (c) 2001-2022 Python Software Foundation.
  All Rights Reserved.

  Copyright (c) 2000 BeOpen.com.
  All Rights Reserved.

  Copyright (c) 1995-2001 Corporation for National Research Initiatives.
  All Rights Reserved.

  Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.
  All Rights Reserved.,
  'credits':     Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
      for supporting Python development.  See www.python.org for more information.,
  'license': Type license() to see the full license text,
  'help': Type help() for interactive help, or help(object) for help about object.,
  'execfile': <function _pydev_imps._pydev_execfile.execfile(file, glob=None, loc=None)>,
  'runfile': <function _pydev_bundle.pydev_umd.runfile(filename, args=None, wdir=None, namespace=None)>,
  '__IPYTHON__': True,
  'display': <function IPython.core.display.display(*objs, include=None, exclude=None, metadata=None, transient=None, display_id=None, **kwargs)>,
  'get_ipython': <bound method InteractiveShell.get_ipython of <ipykernel.zmqshell.ZMQInteractiveShell object at 0x7f9fb1516200>>},
 'a': 666}
[326]:
print(context['a'])
666
[327]:
config_file = '''
SRCDIR = '/tmp/src'
DSTDIR = '/tmp/dst'
INTERVAL = 3
'''

config = {}
exec(config_file, config)
[329]:
config['SRCDIR']
[329]:
'/tmp/src'
[330]:
config['DSTDIR']
[330]:
'/tmp/dst'
[331]:
config['INTERVAL']
[331]:
3