2023-03-13

[1]:
l = [1,2,3,4, 'fuenf']
for element in l:
    print(element)
1
2
3
4
fuenf
[2]:
l
[2]:
[1, 2, 3, 4, 'fuenf']
[3]:
print(type(l))
<class 'list'>
[4]:
i = 42
[5]:
i
[5]:
42
[6]:
print(type(i))
<class 'int'>
[7]:
exec('print("hallo")')
hallo

Syntax

Comment vs Docstring

[8]:
# das ist ein kommentar
[9]:
i = 42 # das ist auch ein kommentar
[10]:
i
[10]:
42
[11]:
# das ist die funktion foo, die hoechst komplex ist und
# die parameter a und b nimmt, die idealerweise integers  sein sollten
def foo(a, b):
    return a+b
[12]:
def foo(a, b):
    'das ist die funktion foo, die hoechst komplex ist und die parameter a und b nimmt, die idealerweise integers  sein sollten'
    return a+b
[13]:
foo.__doc__
[13]:
'das ist die funktion foo, die hoechst komplex ist und die parameter a und b nimmt, die idealerweise integers  sein sollten'
[14]:
help(foo)
Help on function foo in module __main__:

foo(a, b)
    das ist die funktion foo, die hoechst komplex ist und die parameter a und b nimmt, die idealerweise integers  sein sollten

[15]:
foo(1, 2)
[15]:
3
[16]:
add = foo
[17]:
add(2, 3)
[17]:
5
[18]:
add = [1,2,3]
[19]:
try:
    add(2,3)
except Exception as e:
    print(e, type(e))
'list' object is not callable <class 'TypeError'>

Tuple Unpacking

[20]:
l = [1, 'zwei', 3.0]
[21]:
a, b, c = l
[22]:
a
[22]:
1
[23]:
b
[23]:
'zwei'
[24]:
c
[24]:
3.0
[25]:
a, *rest = l
[26]:
a
[26]:
1
[27]:
rest
[27]:
['zwei', 3.0]
[28]:
try:
    a, b = l
except Exception as e:
    print(e, type(e))
too many values to unpack (expected 2) <class 'ValueError'>
[29]:
1, 2
[29]:
(1, 2)
[30]:
a, b
[30]:
(1, 'zwei')
[31]:
tmp = a
a = b
b = tmp
[32]:
a, b
[32]:
('zwei', 1)
[33]:
a, b = b, a

Mutable? Immutable?

[34]:
a = 42
[35]:
id(a)
[35]:
140480285361680
[36]:
b = a
[37]:
id(b)
[37]:
140480285361680
[38]:
a += 1
[39]:
b
[39]:
42
[40]:
a
[40]:
43

Integers

[41]:
i = 2**64 - 1
[42]:
i
[42]:
18446744073709551615
[43]:
hex(i)
[43]:
'0xffffffffffffffff'
[44]:
i += 1
[45]:
i
[45]:
18446744073709551616
[46]:
hex(i)
[46]:
'0x10000000000000000'
[47]:
i += 1
[48]:
i = 2**100
[49]:
i
[49]:
1267650600228229401496703205376
[50]:
2**10000
[50]:
19950631168807583848837421626835850838234968318861924548520089498529438830221946631919961684036194597899331129423209124271556491349413781117593785932096323957855730046793794526765246551266059895520550086918193311542508608460618104685509074866089624888090489894838009253941633257850621568309473902556912388065225096643874441046759871626985453222868538161694315775629640762836880760732228535091641476183956381458969463899410840960536267821064621427333394036525565649530603142680234969400335934316651459297773279665775606172582031407994198179607378245683762280037302885487251900834464581454650557929601414833921615734588139257095379769119277800826957735674444123062018757836325502728323789270710373802866393031428133241401624195671690574061419654342324638801248856147305207431992259611796250130992860241708340807605932320161268492288496255841312844061536738951487114256315111089745514203313820202931640957596464756010405845841566072044962867016515061920631004186422275908670900574606417856951911456055068251250406007519842261898059237118054444788072906395242548339221982707404473162376760846613033778706039803413197133493654622700563169937455508241780972810983291314403571877524768509857276937926433221599399876886660808368837838027643282775172273657572744784112294389733810861607423253291974813120197604178281965697475898164531258434135959862784130128185406283476649088690521047580882615823961985770122407044330583075869039319604603404973156583208672105913300903752823415539745394397715257455290510212310947321610753474825740775273986348298498340756937955646638621874569499279016572103701364433135817214311791398222983845847334440270964182851005072927748364550578634501100852987812389473928699540834346158807043959118985815145779177143619698728131459483783202081474982171858011389071228250905826817436220577475921417653715687725614904582904992461028630081535583308130101987675856234343538955409175623400844887526162643568648833519463720377293240094456246923254350400678027273837755376406726898636241037491410966718557050759098100246789880178271925953381282421954028302759408448955014676668389697996886241636313376393903373455801407636741877711055384225739499110186468219696581651485130494222369947714763069155468217682876200362777257723781365331611196811280792669481887201298643660768551639860534602297871557517947385246369446923087894265948217008051120322365496288169035739121368338393591756418733850510970271613915439590991598154654417336311656936031122249937969999226781732358023111862644575299135758175008199839236284615249881088960232244362173771618086357015468484058622329792853875623486556440536962622018963571028812361567512543338303270029097668650568557157505516727518899194129711337690149916181315171544007728650573189557450920330185304847113818315407324053319038462084036421763703911550639789000742853672196280903477974533320468368795868580237952218629120080742819551317948157624448298518461509704888027274721574688131594750409732115080498190455803416826949787141316063210686391511681774304792596709376
[51]:
3/2
[51]:
1.5
[52]:
3//2
[52]:
1
[53]:
10%2
[53]:
0

Lists

[54]:
l = list()
l = []
l = [1,2,3]
[55]:
len(l)
[55]:
3
[56]:
id(l)
[56]:
140479638276224
[57]:
l.append('vier')
id(l)
[57]:
140479638276224
[58]:
l.extend([5, 'sechs'])
[59]:
l
[59]:
[1, 2, 3, 'vier', 5, 'sechs']
[60]:
l.append([7, 'acht'])
[61]:
l
[61]:
[1, 2, 3, 'vier', 5, 'sechs', [7, 'acht']]
[62]:
l.append(l)
[63]:
l
[63]:
[1, 2, 3, 'vier', 5, 'sechs', [7, 'acht'], [...]]
[64]:
l[1]
[64]:
2
[65]:
l[1] = 'zwei'
[66]:
l
[66]:
[1, 'zwei', 3, 'vier', 5, 'sechs', [7, 'acht'], [...]]
[67]:
'zwei' in l
[67]:
True
[68]:
if 'zwei' in l:
    print('yay')
yay

Tuples

[69]:
t = (1,2,3)
[70]:
type(t)
[70]:
tuple
[71]:
id(t)
[71]:
140480203220736
[72]:
t[1]
[72]:
2
[73]:
try:
    t[1] = 'zwei'
except Exception as e:
    print(e, type(e))
'tuple' object does not support item assignment <class 'TypeError'>
[74]:
try:
    t.append('vier')
except Exception as e:
    print(e, type(e))
'tuple' object has no attribute 'append' <class 'AttributeError'>
[75]:
t += (1,2,3)
[76]:
id(t)
[76]:
140480210406176

Dictionary

[77]:
d = { 'one': 1, 'two': 2 }
[78]:
len(d)
[78]:
2
[79]:
d['one']
[79]:
1
[80]:
d['drei'] = 'three'
[81]:
d['drei']
[81]:
'three'
[82]:
d[4] = 'vier'
[83]:
hash(4)
[83]:
4
[84]:
hash('drei')
[84]:
-7940943354778932823
[85]:
try:
    d[[1,2,3]] = True
except Exception as e:
    print(e, type(e))
unhashable type: 'list' <class 'TypeError'>
[86]:
d
[86]:
{'one': 1, 'two': 2, 'drei': 'three', 4: 'vier'}
[87]:
len(d)
[87]:
4
[88]:
'two' in d
[88]:
True
[89]:
del d['two']
[90]:
'two' in d
[90]:
False

Search by value?

[91]:
for k, v in d.items():
    if v == 1:
        print(k)
one

Exercises

[92]:
l = []
[93]:
l.append(True)
[94]:
l
[94]:
[True]
[95]:
s = '99'
[96]:
i = int(s)
[97]:
i
[97]:
99

DataType Conversiosn

[98]:
s = '123'
[99]:
i = int(s)
[100]:
print(type(i))
<class 'int'>
[101]:
i
[101]:
123
[102]:
s = 'abc'
[103]:
try:
    int(s)
except Exception as e:
    print(e, type(e))
invalid literal for int() with base 10: 'abc' <class 'ValueError'>
[104]:
int(s, 16)
[104]:
2748
[105]:
i
[105]:
123
[106]:
s = str(i)
[107]:
print(type(s))
<class 'str'>
[108]:
l = [1,2,3, 'vier']
print(type(l))
<class 'list'>
[109]:
s
[109]:
'123'
[110]:
s[1]
[110]:
'2'
[111]:
list()
[111]:
[]
[112]:
list('abc')
[112]:
['a', 'b', 'c']
[113]:
try:
    list(666)
except Exception as e:
    print(e, type(s))
'int' object is not iterable <class 'str'>
[114]:
l = list()
l.append('abc')
l
[114]:
['abc']
[115]:
list(['abc'])
[115]:
['abc']
[116]:
['abc']
[116]:
['abc']
[117]:
l = list(range(3))
[118]:
l
[118]:
[0, 1, 2]
[119]:
for element in l:
    print(element)
0
1
2
[120]:
1 in l
[120]:
True
[121]:
2 in l
[121]:
True
[122]:
3 in l
[122]:
False

if

[123]:
i = 2
[124]:
if i == 2:
    print('yay')
yay
[125]:
if i == 3:
    print('yay')

while

sum of numbers 1..100

[128]:
summe = 0
number = 1
while number <= 100:
    summe += number
    number += 1
summe
[128]:
5050
[129]:
sum(range(1, 101))
[129]:
5050
[130]:
i = 42
while i != 42:
    print('noch immer keine antwort')
[133]:
import random
[144]:
while True:
    eyes = random.randrange(1, 7)
    if eyes == 6:
        print('hooray!')
        break
    else:
        print('mist:', eyes)
mist: 4
hooray!
[165]:
n_tries = 0
while n_tries < 6:
    eyes = random.randrange(1, 7)
    if eyes == 6:
        print('hooray!')
        break
    n_tries += 1
else:
    print('versager!')
versager!

range()

[167]:
for element in range(5):
    print(element)
0
1
2
3
4
[173]:
for element in [0,1,2,3,4]:
    print(element)
0
1
2
3
4
[179]:
r = range(5)
[180]:
r
[180]:
range(0, 5)
[181]:
it = iter(r)
[183]:
it
[183]:
<range_iterator at 0x7fc4189e7c90>
[184]:
next(it)
[184]:
0
[185]:
next(it)
[185]:
1
[186]:
next(it)
[186]:
2
[187]:
next(it)
[187]:
3
[188]:
next(it)
[188]:
4
[190]:
try:
    next(it)
except Exception as e:
    print(e, type(e))
 <class 'StopIteration'>

datetime

[217]:
import datetime
[192]:
start = datetime.datetime(year=2023, month=3, day=13, hour=9)
[194]:
start
[194]:
datetime.datetime(2023, 3, 13, 9, 0)
[196]:
step = datetime.timedelta(hours=8)
[198]:
step
[198]:
datetime.timedelta(seconds=28800)
[199]:
start += step
[201]:
start
[201]:
datetime.datetime(2023, 3, 13, 17, 0)
[202]:
start += datetime.timedelta(days=1)
[204]:
start
[204]:
datetime.datetime(2023, 3, 14, 17, 0)
[210]:
datetime.datetime.now()
[210]:
datetime.datetime(2023, 3, 14, 10, 6, 17, 237988)
[215]:
def produce_days(start):
    next = start
    while True:
        yield next
        next += datetime.timedelta(days=1)
[216]:
for day in produce_days(start=datetime.datetime.now()):
    print(day)
    if day > datetime.datetime(year=2023, month=4, day=1):
        break
2023-03-14 10:11:25.374557
2023-03-15 10:11:25.374557
2023-03-16 10:11:25.374557
2023-03-17 10:11:25.374557
2023-03-18 10:11:25.374557
2023-03-19 10:11:25.374557
2023-03-20 10:11:25.374557
2023-03-21 10:11:25.374557
2023-03-22 10:11:25.374557
2023-03-23 10:11:25.374557
2023-03-24 10:11:25.374557
2023-03-25 10:11:25.374557
2023-03-26 10:11:25.374557
2023-03-27 10:11:25.374557
2023-03-28 10:11:25.374557
2023-03-29 10:11:25.374557
2023-03-30 10:11:25.374557
2023-03-31 10:11:25.374557
2023-04-01 10:11:25.374557
[218]:
l = [666, 42]
i = 42
[220]:
i != l
[220]:
True
[221]:
i in l
[221]:
True
[223]:
i not in l
[223]:
False
[224]:
not i in l
[224]:
False
[225]:
6 % 3
[225]:
0
[226]:
6 % 2
[226]:
0
[227]:
7 % 2
[227]:
1
[228]:
7 % 3
[228]:
1
[229]:
7 % 4
[229]:
3
[230]:
7 % 5
[230]:
2
[231]:
7 % 6
[231]:
1

Comprehensions

[233]:
l = [3, 4, 1, 6]
[235]:
l_mal_2 = []
for element in l:
    l_mal_2.append(element*2)
l_mal_2
[235]:
[6, 8, 2, 12]
[238]:
[element*2 for element in l]
[238]:
[6, 8, 2, 12]
[239]:
[element*2 for element in l if element%2==0]
[239]:
[8, 12]

References, (Im)mutability

[248]:
a = 42
[249]:
id(a)
[249]:
140480285361680
[250]:
b = a
[251]:
id(b)
[251]:
140480285361680
[252]:
a += 1
[253]:
id(a)
[253]:
140480285361712
[254]:
b
[254]:
42
[255]:
id(b)
[255]:
140480285361680
[256]:
l1 = [42, 'xy', 13]
id(l1)
[256]:
140479638477760
[257]:
l2 = l1
[258]:
id(l2)
[258]:
140479638477760
[259]:
l1.append(666)
l1
[259]:
[42, 'xy', 13, 666]
[260]:
id(l1)
[260]:
140479638477760
[261]:
id(l2)
[261]:
140479638477760
[262]:
l2
[262]:
[42, 'xy', 13, 666]
[263]:
l3 = l1[:]
[264]:
l3
[264]:
[42, 'xy', 13, 666]
[265]:
l1
[265]:
[42, 'xy', 13, 666]
[267]:
id(l1)
[267]:
140479638477760
[268]:
id(l3)
[268]:
140479638427520
[269]:
l3.append('nochwas')
l3
[269]:
[42, 'xy', 13, 666, 'nochwas']
[270]:
l1
[270]:
[42, 'xy', 13, 666]

Nested lists?

[271]:
l4 = [1, [2,3,4], 5]
len(l4)
[271]:
3
[272]:
l5 = l4[:]
[273]:
id(l4)
[273]:
140480202528192
[274]:
id(l5)
[274]:
140479638428736
[275]:
l4[1].append(666)
[276]:
l5
[276]:
[1, [2, 3, 4, 666], 5]
[278]:
id(l4[1])
[278]:
140480203212992
[279]:
id(l5[1])
[279]:
140480203212992
[280]:
import copy
[281]:
l6 = copy.deepcopy(l5)
[282]:
l6
[282]:
[1, [2, 3, 4, 666], 5]

Functions

[296]:
def maximum(a, b):
    'extremely complex function'
    if a < b:
        return b
    else:
        return a
[285]:
maximum(1, 2)
[285]:
2
[287]:
maximum(1.5, 2.5)
[287]:
2.5
[288]:
maximum('abc', 'def')
[288]:
'def'
[289]:
maximum([1,2], [3,4])
[289]:
[3, 4]
[290]:
maximum([1,2], [1,4])
[290]:
[1, 4]
[292]:
try:
    maximum('abc', 666)
except Exception as e:
    print(e, type(e))
'<' not supported between instances of 'str' and 'int' <class 'TypeError'>
[293]:
True < False
[293]:
False
[295]:
print(type(maximum))
<class 'function'>
[298]:
maximum.__doc__
[298]:
'extremely complex function'
[299]:
a = maximum
[301]:
a(1,2)
[301]:
2
[302]:
id(a)
[302]:
140479598069936
[303]:
id(maximum)
[303]:
140479598069936

Classes?

[313]:
class Person:
    def __init__(self, firstname, lastname, age):
        self.firstname = firstname
        self.lastname = lastname
        self.age = age
    def fullname(self):
        return self.firstname + ' ' + self.lastname
[312]:
joerg = Person('Joerg', 'Faschingbauer', 56)
[309]:
type(joerg)
[309]:
__main__.Person
[314]:
joerg.fullname()
[314]:
'Joerg Faschingbauer'
[317]:
def is_old(p):
    if p.age > 50:
        return True
    else:
        return False
[318]:
is_old(joerg)
[318]:
True
[320]:
Person.old = is_old
[321]:
joerg = Person('Joerg', 'Faschingbauer', 56)
[322]:
joerg.old()
[322]:
True
[325]:
d = {'one': 1, 'two': 2}
[327]:
d['one']
[327]:
1
[328]:
d['three']
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
/tmp/ipykernel_370861/4290492544.py in <module>
----> 1 d['three']

KeyError: 'three'

Strings

[329]:
s = 'abc'
[330]:
s = "abc"
[332]:
s = 'abc\'def'
s
[332]:
"abc'def"
[333]:
s = "abc'def"
s
[333]:
"abc'def"
[334]:
s = 'C:\some\name'
[335]:
print(s)
C:\some
ame
[337]:
s = r'C:\some\name'
print(s)
C:\some\name
[338]:
s = '12345'
s.isdigit()
[338]:
True
[340]:
s = 'abc123'
s.isdigit()
[340]:
False
[341]:
'abc'.center(50)
[341]:
'                       abc                        '
[342]:
s = 'Mississippi'
s.count('ss')
[342]:
2
[343]:
s.count('pp')
[343]:
1
[344]:
'file.csv'.endswith('.csv')
[344]:
True
[345]:
'boot'.endswith('t')
[345]:
True
[347]:
'boot'.count('oo') > 0
[347]:
True
[350]:
'boot'.find('oo') >= 0
[350]:
True
[352]:
'oo' in 'boot'
[352]:
True
[353]:
'boot'.find('oo')
[353]:
1
[355]:
'boot'.find('xxx')
[355]:
-1
[357]:
try:
    'boot'.index('xxx')
except Exception as e:
    print(e, type(e))
substring not found <class 'ValueError'>
[358]:
s = 'Bezahlung Karte   blah |BILLA DANKT blah blah     |BILL blah'
[362]:
fields = s.split('|')
[363]:
fields
[363]:
['Bezahlung Karte   blah ', 'BILLA DANKT blah blah     ', 'BILL blah']
[431]:
';'.join(fields)
[431]:
'Bezahlung Karte   blah ;BILLA DANKT blah blah     ;BILL blah'
[432]:
s = '    \t\n   xxx \n\n\n\t    '
s.strip()
[432]:
'xxx'

Lists

[369]:
l = [1,2,'drei']
l.append(666)
[366]:
l
[366]:
[1, 2, 'drei', 666]
[370]:
l.extend(['noch', 'was'])
l
[370]:
[1, 2, 'drei', 666, 'noch', 'was']
[371]:
l.extend('abc')
l
[371]:
[1, 2, 'drei', 666, 'noch', 'was', 'a', 'b', 'c']
[372]:
l.pop(3)
[372]:
666
[373]:
l
[373]:
[1, 2, 'drei', 'noch', 'was', 'a', 'b', 'c']
[375]:
try:
    l.sort()
except Exception as e:
    print(e, type(e))
'<' not supported between instances of 'str' and 'int' <class 'TypeError'>
[376]:
l.reverse()
[377]:
l
[377]:
['c', 'b', 'a', 'was', 'noch', 'drei', 2, 1]
[378]:
reversed(l)
[378]:
<list_reverseiterator at 0x7fc4189e5030>
[379]:
l = [1,2,3,7,100]
[elem**2 for elem in l]
[379]:
[1, 4, 9, 49, 10000]
[380]:
[elem**2 for elem in l if elem%2==0]
[380]:
[4, 10000]

Dictionaries

[381]:
d = {}
[382]:
d['one'] = 1
[383]:
d
[383]:
{'one': 1}
[384]:
d['one'] = 1.1
[385]:
d
[385]:
{'one': 1.1}
[386]:
d['one']
[386]:
1.1
[388]:
try:
    d['two']
except Exception as e:
    print(e, type(e))
'two' <class 'KeyError'>
[391]:
if d.get('two') is None:
    print('nicht drin')
else:
    print('yay')
nicht drin
[392]:
v = d.get('two', 2)
v
[392]:
2
[393]:
d
[393]:
{'one': 1.1}
[394]:
v = d.setdefault('two', 2)
v
[394]:
2
[395]:
d
[395]:
{'one': 1.1, 'two': 2}
[396]:
del d['two']
d
[396]:
{'one': 1.1}
[401]:
d.update({'two': 2, 'three': 3, 'one': 1})
[402]:
d
[402]:
{'one': 1, 'two': 2, 'three': 3}
[404]:
for elem in d:
    print(elem)
one
two
three
[406]:
for k in d.keys():
    print(k)
one
two
three
[407]:
for v in d.values():
    print(v)
1
2
3
[408]:
for elem in d.items():
    print(elem)
('one', 1)
('two', 2)
('three', 3)
[409]:
for elem in d.items():    # manual tuple unpacking
    k = elem[0]
    v = elem[1]
    print('key:', k, ', value:', v)
key: one , value: 1
key: two , value: 2
key: three , value: 3
[410]:
for elem in d.items():    # semi-manual tuple unpacking
    k, v = elem
    print('key:', k, ', value:', v)
key: one , value: 1
key: two , value: 2
key: three , value: 3
[411]:
for k, v in d.items():
    print('key:', k, ', value:', v)
key: one , value: 1
key: two , value: 2
key: three , value: 3
[413]:
'one' in d
[413]:
True
[414]:
dict
[414]:
dict
[416]:
l = [('one', 1), ('two', 2)]
d = dict(l)
[417]:
d
[417]:
{'one': 1, 'two': 2}

Set

[418]:
s1 = {1,2,3}
s2 = {1,2,3,4}
[419]:
s1.isdisjoint(s2)
[419]:
False
[420]:
s1 < s2
[420]:
True
[421]:
s3 = {0,1,2,3}
s3 < s2
[421]:
False
[423]:
s3 | s2
[423]:
{0, 1, 2, 3, 4}

File IO

[424]:
f = open('/etc/passwd')
f
[424]:
<_io.TextIOWrapper name='/etc/passwd' mode='r' encoding='UTF-8'>
[425]:
f.read()
[425]:
'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\ndbus:x:81:81:System message bus:/:/sbin/nologin\napache:x:48:48:Apache:/usr/share/httpd:/sbin/nologin\ntss:x:59:59:Account used for TPM access:/dev/null:/sbin/nologin\nsystemd-network:x:192:192:systemd Network Management:/:/usr/sbin/nologin\nsystemd-oom:x:999:999:systemd Userspace OOM Killer:/:/usr/sbin/nologin\nsystemd-resolve:x:193:193:systemd Resolver:/:/usr/sbin/nologin\nqemu:x:107:107:qemu user:/:/sbin/nologin\npolkitd:x:998:997:User for polkitd:/:/sbin/nologin\navahi:x:70:70:Avahi mDNS/DNS-SD Stack:/var/run/avahi-daemon:/sbin/nologin\nunbound:x:997:995:Unbound DNS resolver:/etc/unbound:/sbin/nologin\nnm-openconnect:x:996:994:NetworkManager user for OpenConnect:/:/sbin/nologin\ngeoclue:x:995:993:User for geoclue:/var/lib/geoclue:/sbin/nologin\nusbmuxd:x:113:113:usbmuxd user:/:/sbin/nologin\ngluster:x:994:992:GlusterFS daemons:/run/gluster:/sbin/nologin\nrtkit:x:172:172:RealtimeKit:/proc:/sbin/nologin\nchrony:x:993:990::/var/lib/chrony:/sbin/nologin\nsaslauth:x:992:76:Saslauthd user:/run/saslauthd:/sbin/nologin\ndnsmasq:x:991:989:Dnsmasq DHCP and DNS server:/var/lib/dnsmasq:/sbin/nologin\nrpc:x:32:32:Rpcbind Daemon:/var/lib/rpcbind:/sbin/nologin\ncolord:x:990:988:User for colord:/var/lib/colord:/sbin/nologin\nrpcuser:x:29:29:RPC Service User:/var/lib/nfs:/sbin/nologin\nopenvpn:x:989:987:OpenVPN:/etc/openvpn:/sbin/nologin\nnm-openvpn:x:988:986:Default user for running openvpn spawned by NetworkManager:/:/sbin/nologin\npipewire:x:987:985:PipeWire System Daemon:/var/run/pipewire:/sbin/nologin\nabrt:x:173:173::/etc/abrt:/sbin/nologin\nflatpak:x:986:983:User for flatpak system helper:/:/sbin/nologin\ngdm:x:42:42:GNOME Display Manager:/var/lib/gdm:/sbin/nologin\ngnome-initial-setup:x:985:982::/run/gnome-initial-setup/:/sbin/nologin\nvboxadd:x:984: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\nsystemd-coredump:x:978:978:systemd Core Dumper:/:/usr/sbin/nologin\nsystemd-timesync:x:977:977:systemd Time Synchronization:/:/usr/sbin/nologin\nmosquitto:x:976:976:Mosquitto Broker:/etc/mosquitto:/sbin/nologin\n'
[ ]:

[427]:
f = open('/etc/passwd')
f
[427]:
<_io.TextIOWrapper name='/etc/passwd' mode='r' encoding='UTF-8'>
[428]:
f.readlines()
[428]:
['root:x:0:0:root:/root:/bin/bash\n',
 'bin:x:1:1:bin:/bin:/sbin/nologin\n',
 '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',
 'dbus:x:81:81:System message bus:/:/sbin/nologin\n',
 'apache:x:48:48:Apache:/usr/share/httpd:/sbin/nologin\n',
 'tss:x:59:59:Account used for TPM access:/dev/null:/sbin/nologin\n',
 'systemd-network:x:192:192:systemd Network Management:/:/usr/sbin/nologin\n',
 'systemd-oom:x:999:999:systemd Userspace OOM Killer:/:/usr/sbin/nologin\n',
 'systemd-resolve:x:193:193:systemd Resolver:/:/usr/sbin/nologin\n',
 'qemu:x:107:107:qemu user:/:/sbin/nologin\n',
 'polkitd:x:998:997:User for polkitd:/:/sbin/nologin\n',
 'avahi:x:70:70:Avahi mDNS/DNS-SD Stack:/var/run/avahi-daemon:/sbin/nologin\n',
 'unbound:x:997:995:Unbound DNS resolver:/etc/unbound:/sbin/nologin\n',
 'nm-openconnect:x:996:994:NetworkManager user for OpenConnect:/:/sbin/nologin\n',
 'geoclue:x:995:993:User for geoclue:/var/lib/geoclue:/sbin/nologin\n',
 'usbmuxd:x:113:113:usbmuxd user:/:/sbin/nologin\n',
 'gluster:x:994:992:GlusterFS daemons:/run/gluster:/sbin/nologin\n',
 'rtkit:x:172:172:RealtimeKit:/proc:/sbin/nologin\n',
 'chrony:x:993:990::/var/lib/chrony:/sbin/nologin\n',
 'saslauth:x:992:76:Saslauthd user:/run/saslauthd:/sbin/nologin\n',
 'dnsmasq:x:991:989:Dnsmasq DHCP and DNS server:/var/lib/dnsmasq:/sbin/nologin\n',
 'rpc:x:32:32:Rpcbind Daemon:/var/lib/rpcbind:/sbin/nologin\n',
 'colord:x:990:988:User for colord:/var/lib/colord:/sbin/nologin\n',
 'rpcuser:x:29:29:RPC Service User:/var/lib/nfs:/sbin/nologin\n',
 'openvpn:x:989:987:OpenVPN:/etc/openvpn:/sbin/nologin\n',
 'nm-openvpn:x:988:986:Default user for running openvpn spawned by NetworkManager:/:/sbin/nologin\n',
 'pipewire:x:987:985:PipeWire System Daemon:/var/run/pipewire:/sbin/nologin\n',
 'abrt:x:173:173::/etc/abrt:/sbin/nologin\n',
 'flatpak:x:986:983:User for flatpak system helper:/:/sbin/nologin\n',
 'gdm:x:42:42:GNOME Display Manager:/var/lib/gdm:/sbin/nologin\n',
 'gnome-initial-setup:x:985:982::/run/gnome-initial-setup/:/sbin/nologin\n',
 'vboxadd:x:984: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',
 'systemd-coredump:x:978:978:systemd Core Dumper:/:/usr/sbin/nologin\n',
 'systemd-timesync:x:977:977:systemd Time Synchronization:/:/usr/sbin/nologin\n',
 'mosquitto:x:976:976:Mosquitto Broker:/etc/mosquitto:/sbin/nologin\n']
[429]:
f = open('/etc/passwd')
f
[429]:
<_io.TextIOWrapper name='/etc/passwd' mode='r' encoding='UTF-8'>
[430]:
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

String, File IO Exercise

[433]:
line = ''
[434]:
if len(line) == 0:
    print('die ist leer')
die ist leer
[436]:
line = '    \t  '
len(line)
[436]:
7
[437]:
line.strip()
[437]:
''
[439]:
line = '   xxx      '
line.strip()
[439]:
'xxx'
[440]:
line = '    # comment'
line.strip()
[440]:
'# comment'
[441]:
eine_variable = line.strip()
eine_variable
[441]:
'# comment'
[442]:
eine_variable.startswith('#')
[442]:
True
[446]:
line = '  x   y  '
line.replace(' ', '')
[446]:
'xy'
[447]:
line = '    #  '
'#' in line
[447]:
True
[448]:
l = [2,3,4,1,8,666]
[450]:
n = len(l)
[452]:
n
[452]:
6
[454]:
3 in l
[454]:
True
[456]:
1000 in l     # O(n)
[456]:
False
[461]:
s = {2,3,4,1,8,666}
[458]:
3 in s
[458]:
True
[460]:
1000 in s     # O(1)
[460]:
False
[462]:
line = 'xxx yyy'
[464]:
len(line.split(' '))
[464]:
2
[465]:
line = 'xxx  yyy'
[466]:
line.split(' ')
[466]:
['xxx', '', 'yyy']
[467]:
line.split()
[467]:
['xxx', 'yyy']

Pandas

[468]:
persons = {
    'firstname': ['Joerg',                  'Johanna',        'Caro',              'Philipp'          ],
    'lastname':  ['Faschingbauer',          'Faschingbauer',  'Faschingbauer',     'Lichtenberger'    ],
    'email':     ['jf@faschingbauer.co.at', 'caro@email.com', 'johanna@email.com', 'philipp@email.com'],
    'age':       [56,                       27,               25,                  37                 ],
}
[469]:
persons
[469]:
{'firstname': ['Joerg', 'Johanna', 'Caro', 'Philipp'],
 'lastname': ['Faschingbauer',
  'Faschingbauer',
  'Faschingbauer',
  'Lichtenberger'],
 'email': ['jf@faschingbauer.co.at',
  'caro@email.com',
  'johanna@email.com',
  'philipp@email.com'],
 'age': [56, 27, 25, 37]}
[470]:
import pandas as pd
[471]:
data = pd.DataFrame(persons)
[472]:
data
[472]:
firstname lastname email age
0 Joerg Faschingbauer jf@faschingbauer.co.at 56
1 Johanna Faschingbauer caro@email.com 27
2 Caro Faschingbauer johanna@email.com 25
3 Philipp Lichtenberger philipp@email.com 37
[475]:
data['firstname']
[475]:
0      Joerg
1    Johanna
2       Caro
3    Philipp
Name: firstname, dtype: object
[476]:
type(data['firstname'])
[476]:
pandas.core.series.Series
[474]:
data[['firstname', 'lastname']]
[474]:
firstname lastname
0 Joerg Faschingbauer
1 Johanna Faschingbauer
2 Caro Faschingbauer
3 Philipp Lichtenberger
[477]:
persons = data
[479]:
persons.iloc[1]
[479]:
firstname           Johanna
lastname      Faschingbauer
email        caro@email.com
age                      27
Name: 1, dtype: object
[480]:
persons.iloc[1, 2]
[480]:
'caro@email.com'
[481]:
persons.columns
[481]:
Index(['firstname', 'lastname', 'email', 'age'], dtype='object')
[482]:
list(persons.columns)
[482]:
['firstname', 'lastname', 'email', 'age']
[483]:
persons2 = persons.set_index('email')
[486]:
persons2.sort_values('firstname', inplace=True)
[487]:
persons2
[487]:
firstname lastname age
email
johanna@email.com Caro Faschingbauer 25
jf@faschingbauer.co.at Joerg Faschingbauer 56
caro@email.com Johanna Faschingbauer 27
philipp@email.com Philipp Lichtenberger 37
[488]:
flt = (persons['lastname'] == 'Faschingbauer')
flt
[488]:
0     True
1     True
2     True
3    False
Name: lastname, dtype: bool
[494]:
flt.count()
[494]:
4
[497]:
persons.set_index('email', inplace=True)
[498]:
persons.loc['jf@faschingbauer.co.at']
[498]:
firstname            Joerg
lastname     Faschingbauer
age                     56
Name: jf@faschingbauer.co.at, dtype: object
[504]:
persons.loc['jf@faschingbauer.co.at', 'firstname']
[504]:
'Joerg'
[502]:
flt = (persons['lastname'] == 'Faschingbauer')
flt
[502]:
email
jf@faschingbauer.co.at     True
caro@email.com             True
johanna@email.com          True
philipp@email.com         False
Name: lastname, dtype: bool
[505]:
persons.loc[flt, 'firstname']
[505]:
email
jf@faschingbauer.co.at      Joerg
caro@email.com            Johanna
johanna@email.com            Caro
Name: firstname, dtype: object
[506]:
persons['firstname'].isin(['Caro', 'Philipp'])
[506]:
email
jf@faschingbauer.co.at    False
caro@email.com            False
johanna@email.com          True
philipp@email.com          True
Name: firstname, dtype: bool
[508]:
(persons['firstname'] == 'Caro') | (persons['firstname'] == 'Philipp')
[508]:
email
jf@faschingbauer.co.at    False
caro@email.com            False
johanna@email.com          True
philipp@email.com          True
Name: firstname, dtype: bool
[512]:
persons.reset_index(inplace=True)
[513]:
persons
[513]:
email firstname lastname age
0 jf@faschingbauer.co.at Joerg Faschingbauer 56
1 caro@email.com Johanna Faschingbauer 27
2 johanna@email.com Caro Faschingbauer 25
3 philipp@email.com Philipp Lichtenberger 37
[515]:
persons['email']
[515]:
0    jf@faschingbauer.co.at
1            caro@email.com
2         johanna@email.com
3         philipp@email.com
Name: email, dtype: object
[516]:
persons.loc[persons['firstname'].isin(['Caro', 'Philipp'])]
[516]:
email firstname lastname age
2 johanna@email.com Caro Faschingbauer 25
3 philipp@email.com Philipp Lichtenberger 37
[517]:
persons.loc[persons['firstname'].isin(['Caro', 'Philipp']), 'email']
[517]:
2    johanna@email.com
3    philipp@email.com
Name: email, dtype: object
[518]:
persons.loc[persons['firstname'].isin(['Caro', 'Philipp']), 'email'].str.upper()
[518]:
2    JOHANNA@EMAIL.COM
3    PHILIPP@EMAIL.COM
Name: email, dtype: object
[520]:
persons['email'] = persons.loc[persons['firstname'].isin(['Caro', 'Philipp']), 'email'].str.upper()
[521]:
persons
[521]:
email firstname lastname age
0 NaN Joerg Faschingbauer 56
1 NaN Johanna Faschingbauer 27
2 JOHANNA@EMAIL.COM Caro Faschingbauer 25
3 PHILIPP@EMAIL.COM Philipp Lichtenberger 37
[524]:
persons.dropna()
[524]:
email firstname lastname age
2 JOHANNA@EMAIL.COM Caro Faschingbauer 25
3 PHILIPP@EMAIL.COM Philipp Lichtenberger 37
[525]:
persons
[525]:
email firstname lastname age
0 NaN Joerg Faschingbauer 56
1 NaN Johanna Faschingbauer 27
2 JOHANNA@EMAIL.COM Caro Faschingbauer 25
3 PHILIPP@EMAIL.COM Philipp Lichtenberger 37
[531]:
persons['firstname'].str.startswith('J').value_counts()
[531]:
True     2
False    2
Name: firstname, dtype: int64