BlahBlah

[1]:
print('Hello World')
Hello World
[2]:
i = 666
[3]:
type(i)
[3]:
int
[4]:
i = 'hallo'
[5]:
type(i)
[5]:
str
[6]:
i.find('l')
[6]:
2
[7]:
def f(a):
    return a**2
[8]:
type(f)
[8]:
function
[9]:
f(6)
[9]:
36
[10]:
for i in range(5):
    print(i)
0
1
2
3
4
[11]:
code_str = '''
for i in range(5):
    print(i)
'''
[12]:
type(code_str)
[12]:
str
[13]:
exec(code_str)
0
1
2
3
4
[14]:
i
[14]:
4
[15]:
code_str = '''
import random
rnd = random.randrange(6)
'''
[16]:
context = {}
exec(code_str, context)
[17]:
context['rnd']
[17]:
0

Strings und Quotes

[18]:
s = 'abc'
[19]:
print(s)
abc
[20]:
s = "abc"
[21]:
s
[21]:
'abc'
[22]:
print(s)
abc
[23]:
s = 'Hallo, du "Suesser"'
print(s)
Hallo, du "Suesser"
[24]:
s = "Hallo, du 'Suesser'"
print(s)
Hallo, du 'Suesser'
[25]:
s = 'Hallo, du "Suesser" \'du\''
print(s)
Hallo, du "Suesser" 'du'

Comments vs. Docstrings

[26]:
# <doc>
# dieser extrem komplexe algorithmus verwendet ein naeherungsverfahren,
# um die beiden paramete a und b zu addieren.
# die summe ist dann auch der wert des funktionsaufrufs
# </doc>
def add(a,b):
    return a+b
[27]:
s = add(2, 5)
s
[27]:
7
[28]:
def add(a,b):
    '''
    dieser extrem komplexe algorithmus verwendet ein naeherungsverfahren,
    um die beiden paramete a und b zu addieren.
    die summe ist dann auch der wert des funktionsaufrufs
    '''
    return a+b
[29]:
add.__doc__
[29]:
'\n    dieser extrem komplexe algorithmus verwendet ein naeherungsverfahren,\n    um die beiden paramete a und b zu addieren.\n    die summe ist dann auch der wert des funktionsaufrufs \n    '
[30]:
help(add)
Help on function add in module __main__:

add(a, b)
    dieser extrem komplexe algorithmus verwendet ein naeherungsverfahren,
    um die beiden paramete a und b zu addieren.
    die summe ist dann auch der wert des funktionsaufrufs

Variables and Types

[31]:
a = 1.5
type(a)
[31]:
float

Assignment Fun

[32]:
a = 1
b = 2
[33]:
print(a, b, sep=',')
1,2
[34]:
a, b = 1, 2

Swap

[35]:
tmp = a
a = b
b = tmp
[36]:
print(a, b, sep=',')
2,1
[37]:
a, b = 1, 2
[38]:
a, b = b, a
[39]:
print(a, b, sep=',')
2,1

Assignment Details

[40]:
a = 42
id(a)
[40]:
140606563548752
[41]:
b = a
id(b)
[41]:
140606563548752
[42]:
a is b
[42]:
True
[43]:
b += 1
[44]:
b
[44]:
43
[45]:
a
[45]:
42
[46]:
a = 5
[47]:
b
[47]:
43
[48]:
a = 42
b = 42
[49]:
id(a)
[49]:
140606563548752
[50]:
id(b)
[50]:
140606563548752

Datatypes

Boolean

[51]:
1.5 < 42
[51]:
True
[52]:
type(1.5 < 42)
[52]:
bool
[53]:
if 42:
    print('jo eh')
jo eh
[54]:
if 0:
    print('jo eh')
else:
    print('na wirklich net')
na wirklich net
[55]:
a = 1.5 < 42
a
[55]:
True
[56]:
a = 1.5 > 42
a
[56]:
False

Integers

[57]:
i = 1
[58]:
i
[58]:
1
[59]:
i = 1 * 2**0
i
[59]:
1
[60]:
1 * 2**1 + 1 * 2**0
[60]:
3
[61]:
0b11
[61]:
3
[62]:
0b100
[62]:
4
[63]:
1 * 2**2 + 0 * 2**1 + 0 * 2**0
[63]:
4
[64]:
0x10
[64]:
16
[65]:
1 * 16**1 + 0 * 16**0
[65]:
16
[66]:
0o10
[66]:
8
[67]:
1 == 2
[67]:
False
[68]:
1 != 2
[68]:
True
[69]:
3/2
[69]:
1.5
[70]:
3//2
[70]:
1
[71]:
5%2
[71]:
1
[72]:
11%3
[72]:
2
[73]:
if 10%5 == 0:
    print('10 ist durch 5 teilbar')
10 ist durch 5 teilbar

Integers are Infinitely long

[74]:
i = 2**64 - 1
[75]:
i
[75]:
18446744073709551615
[76]:
i += 1
[77]:
i
[77]:
18446744073709551616
[78]:
2**1000
[78]:
10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376

Operator Precedence

[79]:
2*10%3
[79]:
2
[80]:
(2*10)%3
[80]:
2
[81]:
2*(10%3)
[81]:
2
[82]:
2*11%3
[82]:
1
[83]:
(2*11)%3
[83]:
1
[84]:
2*(11%3)
[84]:
4

Floating Point Comparison

[85]:
a = 2/3
b = 4/6
[86]:
a == b  # ERROR!
[86]:
True
[87]:
abs(a-b) < 0.00001
[87]:
True

Datatype Conversions

[88]:
s = '666'
i = 666
[89]:
i == s
[89]:
False
[90]:
type(i) == type(s)
[90]:
False
[91]:
i == int(s)
[91]:
True
[92]:
int(s)
[92]:
666
[93]:
try:
    int('abc')
except Exception as e:
    print(type(e), e)
<class 'ValueError'> invalid literal for int() with base 10: 'abc'
[94]:
int('abc', 16)
[94]:
2748
[95]:
float('1.234')
[95]:
1.234
[96]:
i
[96]:
666
[97]:
bool(i)
[97]:
True
[98]:
bool(0)
[98]:
False
[99]:
if i == 0:
    print('falsch')
[100]:
if i:
    print('true')
true
[101]:
type('abc')
[101]:
str
[102]:
i = 666
s = str(i)
print(s)
666
[103]:
int(666)
[103]:
666
[104]:
int(666.666)
[104]:
666
[105]:
float(666)
[105]:
666.0

Compound Datatypes

List

[106]:
l = [1,2,3,4]
[107]:
len(l)
[107]:
4
[108]:
len('abc')
[108]:
3
[109]:
l.append(5)
[110]:
l
[110]:
[1, 2, 3, 4, 5]
[111]:
l = [1.9, 'drei', 'hansi']
[112]:
l.extend([1, 'one'])
[113]:
l
[113]:
[1.9, 'drei', 'hansi', 1, 'one']
[114]:
l.extend('abc')
[115]:
l
[115]:
[1.9, 'drei', 'hansi', 1, 'one', 'a', 'b', 'c']
[116]:
try:
    l.extend(666)
except Exception as e:
    print(type(e), e)
<class 'TypeError'> 'int' object is not iterable
[117]:
l1 = [1,2,3]
l2 = [2,3,4]
l1 < l2
[117]:
True
[118]:
l1 = [1,2,3]
l2 = [1,2,4]
l1 < l2
[118]:
True
[119]:
s1 = 'abc'
s2 = 'abd'
s1 < s2
[119]:
True

Mutability/Immutability

[120]:
l1 = [1,2,3,4]
l2 = l1
[121]:
l1 is l2
[121]:
True
[122]:
id(l1) == id(l2)
[122]:
True
[123]:
l1.append(5)
[124]:
l1
[124]:
[1, 2, 3, 4, 5]
[125]:
l2
[125]:
[1, 2, 3, 4, 5]
[126]:
i1 = 666
i2 = i1
i1 is i2
[126]:
True
[127]:
i1 += 1
[128]:
i1
[128]:
667
[129]:
i2
[129]:
666
[130]:
id(i2)
[130]:
140606428182128
[131]:
id(i1)
[131]:
140606428182896
[132]:
l1 is l2
[132]:
True
[133]:
l1
[133]:
[1, 2, 3, 4, 5]
[134]:
l2
[134]:
[1, 2, 3, 4, 5]
[135]:
l1 = [1,2,3,4]
l2 = l1[:]
[136]:
l1.append(5)
l1
[136]:
[1, 2, 3, 4, 5]
[137]:
l2
[137]:
[1, 2, 3, 4]
[138]:
l1 = [1, 2, ['a', 'b'], 3, 4]
l2 = l1[:]
[139]:
l1.append(5)
[140]:
l1
[140]:
[1, 2, ['a', 'b'], 3, 4, 5]
[141]:
l2
[141]:
[1, 2, ['a', 'b'], 3, 4]
[142]:
l2[2].append('c')
[143]:
l2
[143]:
[1, 2, ['a', 'b', 'c'], 3, 4]
[144]:
l1
[144]:
[1, 2, ['a', 'b', 'c'], 3, 4, 5]

Tuple

[145]:
t = (1,2,3,4)
[146]:
for element in t:
    print(element)
1
2
3
4
[147]:
try:
    t.append(5)
except Exception as e:
    print(type(e), e)
<class 'AttributeError'> 'tuple' object has no attribute 'append'

Liste mit einem Element:

[148]:
l = [1]
[149]:
type(l)
[149]:
list
[150]:
l
[150]:
[1]

Tuple mit einem Element?

[151]:
t = (1)
[152]:
type(t)
[152]:
int
[153]:
3*(4%2)
[153]:
0
[154]:
t = (1,)
[155]:
type(t)
[155]:
tuple

in Operator

[156]:
l = [4,1,8,2,44,0]
[157]:
5 in l
[157]:
False
[158]:
5 not in l
[158]:
True
[159]:
4 in l
[159]:
True

Dictionary

[160]:
people = {
    '1037190666': ('Joerg', 'Faschingbauer', '19.6.1966'),
    '1234250497': ('Caro', 'Faschingbauer', '25.4.1997'),
}
[161]:
people['1037190666']
[161]:
('Joerg', 'Faschingbauer', '19.6.1966')
[162]:
try:
    people['2345010101']
except Exception as e:
    print(type(e), e)
<class 'KeyError'> '2345010101'
[163]:
people['2345010101'] = ('Elizabeth', 'Queen', '1.1.1901')
[164]:
people['2345010101']
[164]:
('Elizabeth', 'Queen', '1.1.1901')
[165]:
del people['2345010101']
[166]:
'2345010101' in people
[166]:
False

Set

[167]:
s = {'Joerg', 'Caro', 'Johanna', 'Philipp'}
[168]:
'Joerg' in s
[168]:
True
[169]:
s.add('Evi')
[170]:
'Evi' in s
[170]:
True
[171]:
s.remove('Joerg')

Exercise: Digit To English Word

[172]:
translation_table = { 0: 'zero', 1: 'one', 2: 'two' }
[173]:
zahl = '2'
zahl = int(zahl)
[174]:
translation = translation_table[zahl]
[175]:
print(translation)
two

Exercise: Determine Maximum of Two Numbers

[176]:
l, r = 200, 99     # tuple unpacking
[177]:
if l < r:
    print(r)
else:
    print(l)
200
[178]:
max(l, r)
[178]:
200
[179]:
max(200, 99, 356, 1)
[179]:
356
[180]:
numbers = [200, 99, 356, 1]

Iterable?

[181]:
for element in numbers:
    print(element)
200
99
356
1
[182]:
for element in 'abc':
    print(element)
a
b
c
[183]:
max(numbers)
[183]:
356

Strings are iterable

[184]:
max('abc')
[184]:
'c'

Slicing

[185]:
numbers
[185]:
[200, 99, 356, 1]
[186]:
numbers[1]
[186]:
99
[187]:
numbers[2]
[187]:
356
[188]:
try:
    numbers[4]
except Exception as e:
    print(type(e), e)
<class 'IndexError'> list index out of range
[189]:
numbers[1:3]
[189]:
[99, 356]
[190]:
numbers[1:4]
[190]:
[99, 356, 1]
[191]:
numbers[1:len(numbers)]
[191]:
[99, 356, 1]
[192]:
numbers[1:]
[192]:
[99, 356, 1]

while Loops

[193]:
summe = 0
i = 1

while i <= 100:
    summe += i
    i += 1

print(summe)
5050

Pythonicity

[194]:
sum(range(1, 101))
[194]:
5050

Use Case: maximal sechs mal wuerfeln, sich freuen, wenn eine Sechser faellt, und sonst jammern

Version 1: potschert, weil wir nicht jammern

[195]:
import random

versuch_nummer = 1
while versuch_nummer <= 6:
    augen = random.randrange(1,7)
    if augen == 6:
        print('yay!, nach', versuch_nummer, 'versuchen')
        break
    versuch_nummer += 1

print('ende')
yay!, nach 2 versuchen
ende

Version 2: potschertes Jammern

[196]:
import random

versuch_nummer = 1
yay = False
while versuch_nummer <= 6:
    augen = random.randrange(1,7)
    if augen == 6:
        print('yay!, nach', versuch_nummer, 'versuchen')
        yay = True
        break
    versuch_nummer += 1

if not yay:
    print('Jammertal!!!!')
Jammertal!!!!

Version 3: Pythonic jammern

[197]:
import random

versuch_nummer = 1
while versuch_nummer <= 6:
    augen = random.randrange(1,7)
    if augen == 6:
        print('yay!, nach', versuch_nummer, 'versuchen')
        break
    versuch_nummer += 1
else:
    print('Jammertal!!!!')
yay!, nach 1 versuchen

Ranges

[198]:
numbers = [3, 2, 7, 99, 5, 3]
[199]:
numbers[2:5]
[199]:
[7, 99, 5]
[200]:
s = 'Hello World'
[201]:
s[6:10]
[201]:
'Worl'
[202]:
s[0:5]
[202]:
'Hello'
[203]:
s[0:5:2]
[203]:
'Hlo'
[204]:
for i in range(5):
    print(i)
0
1
2
3
4
[205]:
for i in range(0,5):
    print(i)
0
1
2
3
4
[206]:
for i in range(2,5):
    print(i)
2
3
4
[207]:
for i in range(2,7,2):
    print(i)
2
4
6

Exercise: Sort out Duplicates

[208]:
output_liste = [2, 3, 1]
[209]:
element = 1
if element in output_liste:
    print('jo eh')
jo eh

Set

[210]:
have = set()
[211]:
have.add(2)
have.add(3)
have.add(1)
[212]:
1 in have
[212]:
True
[213]:
10 in have
[213]:
False

dict.fromkeys()

Set does not preserve insertion order

[214]:
s = set()
s.add(100)
s.add(1)
s.add(50)
for element in s:
    print(element)
1
50
100

Dictionary preserves Insertion Order

[215]:
d = {}
d[100] = 'x'
d[1] = 'x'
d[50] = 'x'
for element in d:
    print(element)
100
1
50
[216]:
input_list = [2, 3, 1, 10, 3, 3, 1, 10, 5, 2]
[217]:
d = dict.fromkeys(input_list)
d
[217]:
{2: None, 3: None, 1: None, 10: None, 5: None}
[218]:
for element in d:
    print(element)
2
3
1
10
5
[219]:
output_list = list(d)
output_list
[219]:
[2, 3, 1, 10, 5]
[220]:
list('abc')
[220]:
['a', 'b', 'c']

Algorithmic Complexity

O(n)

[221]:
l = [2,3,4,1,5,7,8]
100 in l
[221]:
False

More on Lists

[222]:
l = [3,2,1,5,6]
l.append(3000)
l
[222]:
[3, 2, 1, 5, 6, 3000]
[223]:
l.insert(2, 'blah')
[224]:
l
[224]:
[3, 2, 'blah', 1, 5, 6, 3000]
[225]:
l.insert(0, 'erstes/nulltes')
l
[225]:
['erstes/nulltes', 3, 2, 'blah', 1, 5, 6, 3000]
[226]:
l.reverse()
l
[226]:
[3000, 6, 5, 1, 'blah', 2, 3, 'erstes/nulltes']
[227]:
l.reverse()
l
[227]:
['erstes/nulltes', 3, 2, 'blah', 1, 5, 6, 3000]
[228]:
r = reversed(l)
[229]:
type(r)
[229]:
list_reverseiterator
[230]:
for element in r:
    print(element)
3000
6
5
1
blah
2
3
erstes/nulltes
[231]:
try:
    l.sort()
except Exception as e:
    print(type(e), e)
<class 'TypeError'> '<' not supported between instances of 'int' and 'str'
[232]:
l = [2, 6, 1, 89, 1, 34567654567]
l.sort()
[233]:
l
[233]:
[1, 1, 2, 6, 89, 34567654567]
[234]:
l = [2, 6, 1, 89, 34567654567]
[235]:
s = sorted(l)
s
[235]:
[1, 2, 6, 89, 34567654567]
[236]:
l
[236]:
[2, 6, 1, 89, 34567654567]
[237]:
l = [2,1,3,4]
del l[1]
l
[237]:
[2, 3, 4]
[238]:
el = l.pop(2)
el
[238]:
4
[239]:
l
[239]:
[2, 3]

Type names are callable

[282]:
list('abc')
[282]:
['a', 'b', 'c']

More On Dictionaries

[240]:
table = { 'one': 1, 'two': 2 }
[241]:
table['one']
[241]:
1
[242]:
table['three'] = 3
[243]:
'three' in table
[243]:
True
[244]:
try:
    table['four']
except Exception as e:
    print(type(e), e)
<class 'KeyError'> 'four'
[245]:
value = table.get('four')
[246]:
print(value)
None
[247]:
if value is None:
    print('leider nicht')
else:
    print('gsd')
leider nicht
[248]:
value = table.get('four', 4)
print(value)
4
[249]:
'four' in table
[249]:
False
[250]:
'one' in table
[250]:
True
[251]:
del table['one']
[252]:
'one' in table
[252]:
False
[253]:
table
[253]:
{'two': 2, 'three': 3}
[254]:
table.setdefault('three', 3)
[254]:
3
[255]:
table.setdefault('one', 1)
[255]:
1
[256]:
table
[256]:
{'two': 2, 'three': 3, 'one': 1}

Dictionary Iteration

Keys …

[257]:
for element in table:
    print(element)
two
three
one
[258]:
for k in table.keys():
    print(k)
two
three
one
[259]:
for v in table.values():
    print(v)
2
3
1
[260]:
for element in table.items():
    print(element)
('two', 2)
('three', 3)
('one', 1)

Tuple unpacking

[265]:
a, b = 1, 2
[264]:
a, b = b, a
[263]:
(a, b) = (1, 2)
[267]:
for element in table.items():
    k, v = element
    print('Key:', k, ', Value:', v)
Key: two , Value: 2
Key: three , Value: 3
Key: one , Value: 1
[268]:
for k, v in table.items():
    print('Key:', k, ', Value:', v)
Key: two , Value: 2
Key: three , Value: 3
Key: one , Value: 1

Tuple unpacking — CSV

[269]:
csv = [
    ['1037190666', 'Joerg', 'Faschingbauer'],
    ['1234250497', 'Caro', 'Faschingbauer'],
]
[270]:
for svnr, firstname, lastname in csv:
    print(f'SVNr: {svnr}, Firstname: {firstname}, Lastname: {lastname}')
SVNr: 1037190666, Firstname: Joerg, Lastname: Faschingbauer
SVNr: 1234250497, Firstname: Caro, Lastname: Faschingbauer
[272]:
try:
    for svnr, firstname in csv:
        pass
except Exception as e:
    print(type(e), e)
<class 'ValueError'> too many values to unpack (expected 2)
[274]:
for svnr, firstname, _ in csv:
    pass

``dict.update()``

[275]:
table = { 'one': 1, 'two': 2 }
[276]:
another_table = {'one': 100, 'three': 300}
[277]:
table.update(another_table)
[278]:
table
[278]:
{'one': 100, 'two': 2, 'three': 300}

Type names are callable

[283]:
pairs = [('1037190666', 'Joerg'), ('1234250497', 'Caro')]
[284]:
dict(pairs)
[284]:
{'1037190666': 'Joerg', '1234250497': 'Caro'}

More On Sets

[279]:
s1 = {1, 2, 3, 4}
s2 = {3, 4, 5, 6}
[281]:
s1 ^ s2     # symmetische differenz
[281]:
{1, 2, 5, 6}

Type names are callable

[288]:
set('abc')
[288]:
{'a', 'b', 'c'}
[287]:
set([1,3,2,5,6])
[287]:
{1, 2, 3, 5, 6}

eval(), json

eval()

[1]:
s = '666'
[2]:
int(s)
[2]:
666
[3]:
eval(s)
[3]:
666
[6]:
eval('666.66')
[6]:
666.66
[8]:
eval('"abc"')
[8]:
'abc'
[9]:
eval('{1: "one", 2: "two"}')
[9]:
{1: 'one', 2: 'two'}

WARUM TF? Netzwerkkommunikation, vielleicht?

Client …

[16]:
import time

request_to_send = {
    'action': 'scan',
    'timestamp': time.time(),
}

request_str_to_send = repr(request_to_send)

# send off request_str_to_send
[17]:
repr(request_to_send)
[17]:
"{'action': 'scan', 'timestamp': 1651046407.3633313}"

Server … (reads request off the cable)

[14]:
# read request (as str) off cable
request_str_from_cable = request_str_to_send

request_from_cable = eval(request_str_from_cable)
[18]:
request_from_cable
[18]:
{'action': 'scan', 'timestamp': 1651046335.8477345}

json

[19]:
import json

Client …

[21]:
request_to_send
[21]:
{'action': 'scan', 'timestamp': 1651046407.3633313}
[22]:
request_str_to_send = json.dumps(request_to_send)
request_str_to_send
[22]:
'{"action": "scan", "timestamp": 1651046407.3633313}'

sends off request_str_to_send …

Server …

reads request from cable

[24]:
request_str_from_cable = request_str_to_send
[25]:
request_from_cable = json.loads(request_str_from_cable)
request_from_cable
[25]:
{'action': 'scan', 'timestamp': 1651046407.3633313}

References, (Im)mutability

[26]:
t = ('abc', 2, {}, [])
[52]:
try:
    t.append(666)
except Exception as e:
    print(type(e), e)
<class 'AttributeError'> 'tuple' object has no attribute 'append'
[54]:
try:
    t[2] = 0
except Exception as e:
    print(type(e), e)
<class 'TypeError'> 'tuple' object does not support item assignment
[29]:
d = t[2]
l = t[3]
[31]:
d
[31]:
{}
[32]:
l
[32]:
[]
[33]:
l.append(666)
[34]:
t
[34]:
('abc', 2, {}, [666])
[35]:
d['one'] = 1
[36]:
t
[36]:
('abc', 2, {'one': 1}, [666])
[37]:
id(t[3])
[37]:
139909434561408
[38]:
id(l)
[38]:
139909434561408
[39]:
i = 42
[40]:
id(i)
[40]:
139909544402512
[41]:
i += 1
[42]:
id(i)
[42]:
139909544402544
[43]:
s = 'abc'
id(s)
[43]:
139909543772528
[46]:
s += 'def'
id(s)
[46]:
139909433666288
[47]:
import sys
sys.getrefcount(s)
[47]:
2
[48]:
l = [1,2,3]
l.append(l)
[49]:
l
[49]:
[1, 2, 3, [...]]
[50]:
import copy
copy.deepcopy(l)
[50]:
[1, 2, 3, [...]]
[51]:
del l

File I/O

Open for reading …

[59]:
f = open('/etc/passwd', mode='r')
[60]:
f.read(10)
[60]:
'root:x:0:0'
[61]:
f.read(10)
[61]:
':root:/roo'
[62]:
f.read()
[62]:
't:/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'
[64]:
f.read()     # EOF (end of file)
[64]:
''
[65]:
f = open('/etc/passwd')
[66]:
f.readline()
[66]:
'root:x:0:0:root:/root:/bin/bash\n'
[67]:
f.readline()
[67]:
'bin:x:1:1:bin:/bin:/sbin/nologin\n'
[68]:
f.readlines()
[68]:
['daemon:x:2:2:daemon:/sbin:/sbin/nologin\n',
 'adm:x:3:4:adm:/var/adm:/sbin/nologin\n',
 'lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin\n',
 'sync:x:5:0:sync:/sbin:/bin/sync\n',
 'shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown\n',
 'halt:x:7:0:halt:/sbin:/sbin/halt\n',
 'mail:x:8:12:mail:/var/spool/mail:/sbin/nologin\n',
 'operator:x:11:0:operator:/root:/sbin/nologin\n',
 'games:x:12:100:games:/usr/games:/sbin/nologin\n',
 'ftp:x:14:50:FTP User:/var/ftp:/sbin/nologin\n',
 'nobody:x:65534:65534:Kernel Overflow User:/:/sbin/nologin\n',
 'apache:x:48:48:Apache:/usr/share/httpd:/sbin/nologin\n',
 'systemd-network:x:192:192:systemd Network Management:/:/sbin/nologin\n',
 'systemd-coredump:x:999:997:systemd Core Dumper:/:/sbin/nologin\n',
 'systemd-resolve:x:193:193:systemd Resolver:/:/sbin/nologin\n',
 'systemd-oom:x:998:996:systemd Userspace OOM Killer:/:/sbin/nologin\n',
 'systemd-timesync:x:997:995:systemd Time Synchronization:/:/sbin/nologin\n',
 'tss:x:59:59:Account used for TPM access:/dev/null:/sbin/nologin\n',
 'dbus:x:81:81:System message bus:/:/sbin/nologin\n',
 'polkitd:x:996:994:User for polkitd:/:/sbin/nologin\n',
 'avahi:x:70:70:Avahi mDNS/DNS-SD Stack:/var/run/avahi-daemon:/sbin/nologin\n',
 'unbound:x:995:992:Unbound DNS resolver:/etc/unbound:/sbin/nologin\n',
 'dnsmasq:x:994:991:Dnsmasq DHCP and DNS server:/var/lib/dnsmasq:/sbin/nologin\n',
 'nm-openconnect:x:993:989:NetworkManager user for OpenConnect:/:/sbin/nologin\n',
 'usbmuxd:x:113:113:usbmuxd user:/:/sbin/nologin\n',
 'gluster:x:992:988:GlusterFS daemons:/run/gluster:/sbin/nologin\n',
 'rtkit:x:172:172:RealtimeKit:/proc:/sbin/nologin\n',
 'pipewire:x:991:987:PipeWire System Daemon:/var/run/pipewire:/sbin/nologin\n',
 'geoclue:x:990:986:User for geoclue:/var/lib/geoclue:/sbin/nologin\n',
 'chrony:x:989:984::/var/lib/chrony:/sbin/nologin\n',
 'saslauth:x:988:76:Saslauthd user:/run/saslauthd:/sbin/nologin\n',
 'radvd:x:75:75:radvd user:/:/sbin/nologin\n',
 'rpc:x:32:32:Rpcbind Daemon:/var/lib/rpcbind:/sbin/nologin\n',
 'qemu:x:107:107:qemu user:/:/sbin/nologin\n',
 'openvpn:x:987:982:OpenVPN:/etc/openvpn:/sbin/nologin\n',
 'nm-openvpn:x:986:981:Default user for running openvpn spawned by NetworkManager:/:/sbin/nologin\n',
 'colord:x:985:980:User for colord:/var/lib/colord:/sbin/nologin\n',
 'rpcuser:x:29:29:RPC Service User:/var/lib/nfs:/sbin/nologin\n',
 'abrt:x:173:173::/etc/abrt:/sbin/nologin\n',
 'flatpak:x:984:979:User for flatpak system helper:/:/sbin/nologin\n',
 'gdm:x:42:42::/var/lib/gdm:/sbin/nologin\n',
 'gnome-initial-setup:x:983:978::/run/gnome-initial-setup/:/sbin/nologin\n',
 'vboxadd:x:982:1::/var/run/vboxadd:/sbin/nologin\n',
 'sshd:x:74:74:Privilege-separated SSH:/usr/share/empty.sshd:/sbin/nologin\n',
 'tcpdump:x:72:72::/:/sbin/nologin\n',
 'jfasch:x:1000:1000:Joerg Faschingbauer:/home/jfasch:/bin/bash\n',
 'mosquitto:x:981:974:Mosquitto Broker:/etc/mosquitto:/sbin/nologin\n',
 'someone-else:x:1001:1001::/home/someone-else:/bin/bash\n']
[69]:
f = open('/etc/passwd')
[70]:
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

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

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

systemd-coredump:x:999:997:systemd Core Dumper:/:/sbin/nologin

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

systemd-oom:x:998:996:systemd Userspace OOM Killer:/:/sbin/nologin

systemd-timesync:x:997:995:systemd Time Synchronization:/:/sbin/nologin

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

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

polkitd:x:996:994:User for polkitd:/:/sbin/nologin

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

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

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

nm-openconnect:x:993:989:NetworkManager user for OpenConnect:/:/sbin/nologin

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

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

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

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

geoclue:x:990:986:User for geoclue:/var/lib/geoclue:/sbin/nologin

chrony:x:989:984::/var/lib/chrony:/sbin/nologin

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

radvd:x:75:75:radvd user:/:/sbin/nologin

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

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

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

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

colord:x:985:980:User for colord:/var/lib/colord:/sbin/nologin

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

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

flatpak:x:984:979:User for flatpak system helper:/:/sbin/nologin

gdm:x:42:42::/var/lib/gdm:/sbin/nologin

gnome-initial-setup:x:983:978::/run/gnome-initial-setup/:/sbin/nologin

vboxadd:x:982: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

mosquitto:x:981:974:Mosquitto Broker:/etc/mosquitto:/sbin/nologin

someone-else:x:1001:1001::/home/someone-else:/bin/bash

[72]:
try:
    f = open('/etc/passwd', 'w')
except Exception as e:
    print(type(e), e)
<class 'PermissionError'> [Errno 13] Permission denied: '/etc/passwd'

Encoding

[74]:
s = 'abc'
bytes = s.encode('ascii')
[75]:
len(bytes)
[75]:
3
[76]:
bytes[0]
[76]:
97
[77]:
bytes[1]
[77]:
98
[79]:
s = 'Jörg'
try:
    s.encode('ascii')
except Exception as e:
    print(type(e), e)
<class 'UnicodeEncodeError'> 'ascii' codec can't encode character '\xf6' in position 1: ordinal not in range(128)
[81]:
bytes = s.encode('iso-8859-1')
len(bytes)
[81]:
4
[82]:
bytes[1]
[82]:
246
[83]:
s
[83]:
'Jörg'
[85]:
joerg_latin = s.encode('iso-8859-1')
[86]:
type(joerg_latin)
[86]:
bytes
[87]:
len(bytes)
[87]:
4
[88]:
joerg_latin
[88]:
b'J\xf6rg'
[89]:
joerg_latin.decode('iso-8859-5')
[89]:
'Jіrg'

enumerate()

[90]:
names = ['Joerg', 'Caro', 'Philipp', 'Johanna']
for n in names:
    print(n)
Joerg
Caro
Philipp
Johanna
[92]:
for element in enumerate(names):
    print(element)
(0, 'Joerg')
(1, 'Caro')
(2, 'Philipp')
(3, 'Johanna')
[93]:
for lineno, n in enumerate(names):
    print(lineno, n)
0 Joerg
1 Caro
2 Philipp
3 Johanna