Python Basics (2023-06-20 - 2023-06-22)

[1]:
a = 1
b = 2
[2]:
print(a)
1
[3]:
print(b)
2
[4]:
c, d = 3, 4
[5]:
t = (3, 4)
type(t)
[5]:
tuple
[6]:
t = (3, 4, 5)
[7]:
type(t)
[7]:
tuple
[8]:
tmp = c
c = d
d = tmp
[9]:
c, d
[9]:
(4, 3)
[10]:
c, d = d, c
[11]:
a = 42
[12]:
id(a)
[12]:
140640823526928
[13]:
hex(id(a))
[13]:
'0x7fe97e53c610'
[14]:
b = a
[15]:
id(b)
[15]:
140640823526928
[16]:
a += 1
[17]:
id(a)
[17]:
140640823526960
[18]:
del b
[19]:
try:
    b
except NameError as e:
    print('NameError(specific)')
except Exception as e:
    print(e, type(e))
NameError(specific)
[20]:
b = None
[21]:
type(b)
[21]:
NoneType
[22]:
print(b)
None

DataTypes

Integers

[23]:
i = 2**64-1
[24]:
hex(i)
[24]:
'0xffffffffffffffff'
[25]:
i += 1
[26]:
i
[26]:
18446744073709551616
[27]:
hex(i)
[27]:
'0x10000000000000000'
[28]:
2**1000
[28]:
10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376

Datatype Conversions

[29]:
s = '666'
int(s)
[29]:
666
[30]:
int('0xdeadbeef', 16)
[30]:
3735928559
[31]:
int('666', 7)
[31]:
342
[32]:
str(666)
[32]:
'666'
[33]:
float(666)
[33]:
666.0
[34]:
float('42.666')
[34]:
42.666

(Im)mutable?

[35]:
l = [1, 2, 3]
[36]:
id(l)
[36]:
140640741310912
[37]:
l.append(4)
[38]:
l
[38]:
[1, 2, 3, 4]
[39]:
id(l)
[39]:
140640741310912
[40]:
t = (1,2,3)
[41]:
id(t)
[41]:
140640741034048
[42]:
try:
    t.append(4)
except Exception as e:
    print(e, type(e))
'tuple' object has no attribute 'append' <class 'AttributeError'>

Compound Datatypes

List

[43]:
l = [1, 2, 3, 'vier']
[44]:
id(l)
[44]:
140640741341184
[45]:
l
[45]:
[1, 2, 3, 'vier']
[46]:
l.append(5.0)
[47]:
l
[47]:
[1, 2, 3, 'vier', 5.0]
[48]:
len(l)
[48]:
5
[49]:
l.extend([6, 7, 'acht'])
[50]:
l
[50]:
[1, 2, 3, 'vier', 5.0, 6, 7, 'acht']
[51]:
l.append([9, 10])
[52]:
l
[52]:
[1, 2, 3, 'vier', 5.0, 6, 7, 'acht', [9, 10]]
[53]:
del l[8]
[54]:
l
[54]:
[1, 2, 3, 'vier', 5.0, 6, 7, 'acht']
[55]:
for elem in l:
    print(type(elem))
<class 'int'>
<class 'int'>
<class 'int'>
<class 'str'>
<class 'float'>
<class 'int'>
<class 'int'>
<class 'str'>
[56]:
[type(elem) for elem in l]
[56]:
[int, int, int, str, float, int, int, str]
[57]:
[elem for elem in l if type(elem) is not list]
[57]:
[1, 2, 3, 'vier', 5.0, 6, 7, 'acht']
[58]:
for e in l:
    print(e)
1
2
3
vier
5.0
6
7
acht
[59]:
l += [9,10]
[60]:
id(l)
[60]:
140640741341184
[61]:
l
[61]:
[1, 2, 3, 'vier', 5.0, 6, 7, 'acht', 9, 10]
[62]:
1 in l
[62]:
True
[63]:
2 in l
[63]:
True
[64]:
10 in l
[64]:
True
[65]:
666 in l
[65]:
False

Dictionary

[66]:
d = {'one': 1, 'two': 2, 3: 'three'}
[67]:
d['one']
[67]:
1
[68]:
d[3]
[68]:
'three'
[69]:
len(d)
[69]:
3
[70]:
del d[3]
[71]:
try:
    del d[2]
except Exception as e:
    print(e, type(e))
2 <class 'KeyError'>
[72]:
d['three'] = 3
[73]:
'three' in d
[73]:
True
[74]:
'four' in d
[74]:
False
[75]:
d['three'] = 3.0
[76]:
d
[76]:
{'one': 1, 'two': 2, 'three': 3.0}
[77]:
d['three'] = [3, 3.0, 'drei']
[78]:
d
[78]:
{'one': 1, 'two': 2, 'three': [3, 3.0, 'drei']}
[79]:
type(d)
[79]:
dict
[80]:
'four' in d
[80]:
False
[81]:
try:
    d['four']
except Exception as e:
    print(e, type(e))
'four' <class 'KeyError'>
[82]:
elem = d.get('four')
if elem is None:
    elem = 4
print(elem)
4
[83]:
elem = d.get('four', 4)
print(elem)
4

Exercise: Mixed List, Interactive Interpreter

[84]:
l = []
[85]:
l.append(42)
[86]:
l
[86]:
[42]
[87]:
l.append(42.666)
l.append(True)
l.append('abc')
[88]:
l
[88]:
[42, 42.666, True, 'abc']
[89]:
l.append([1,2,'drei'])
[90]:
l
[90]:
[42, 42.666, True, 'abc', [1, 2, 'drei']]
[91]:
l.append((1, 2, 'drei'))
[92]:
l
[92]:
[42, 42.666, True, 'abc', [1, 2, 'drei'], (1, 2, 'drei')]
[93]:
l.append({1,2,3})
[94]:
l
[94]:
[42, 42.666, True, 'abc', [1, 2, 'drei'], (1, 2, 'drei'), {1, 2, 3}]
[95]:
l.append({1:'one', 2:'two'})
[96]:
l
[96]:
[42,
 42.666,
 True,
 'abc',
 [1, 2, 'drei'],
 (1, 2, 'drei'),
 {1, 2, 3},
 {1: 'one', 2: 'two'}]

len(), range(), for

[97]:
len(l)
[97]:
8
[98]:
for elem in l:
    print(elem)
42
42.666
True
abc
[1, 2, 'drei']
(1, 2, 'drei')
{1, 2, 3}
{1: 'one', 2: 'two'}
[99]:
l = [0,1,2,3,4]
for elem in l:
    print(elem)
0
1
2
3
4
[100]:
for elem in range(5):
    print(elem)
0
1
2
3
4
[101]:
elem = 0
while elem < 5:
    print(elem)
    elem += 1
0
1
2
3
4
[102]:
d
[102]:
{'one': 1, 'two': 2, 'three': [3, 3.0, 'drei']}
[103]:
for k in d:
    print(k)
one
two
three
[104]:
for k in d.keys():
    print(k)
one
two
three
[105]:
for v in d.values():
    print(v)
1
2
[3, 3.0, 'drei']
[106]:
for wasjetzt in d.items():
    print(wasjetzt)
('one', 1)
('two', 2)
('three', [3, 3.0, 'drei'])
[107]:
for elem in d.items():
    k = elem[0]
    v = elem[1]
    print('key: ', k, ', value: ', v)
key:  one , value:  1
key:  two , value:  2
key:  three , value:  [3, 3.0, 'drei']
[108]:
for k, v in d.items():
    print('key: ', k, ', value: ', v)
key:  one , value:  1
key:  two , value:  2
key:  three , value:  [3, 3.0, 'drei']

References, (Im)mutability

[109]:
a = 42
[110]:
id(a)
[110]:
140640823526928
[111]:
b = a
[112]:
id(b)
[112]:
140640823526928
[113]:
id(a) == id(b)
[113]:
True
[114]:
a is b
[114]:
True
[115]:
a == b
[115]:
True
[116]:
l1 = [1, 2, 3]
[117]:
id(l1)
[117]:
140640722624768
[118]:
l2 = [1, 2, 3]
[119]:
id(l2)
[119]:
140640722715136
[120]:
l1.append(4)
[121]:
l1
[121]:
[1, 2, 3, 4]
[122]:
l2
[122]:
[1, 2, 3]
[123]:
l1 is l2
[123]:
False
[124]:
l1
[124]:
[1, 2, 3, 4]
[125]:
l1_copy = l1
[126]:
l1_copy is l1
[126]:
True
[127]:
id(l1_copy) == id(l1)
[127]:
True
[128]:
l1.append(5)
[129]:
l1
[129]:
[1, 2, 3, 4, 5]
[130]:
l1_copy
[130]:
[1, 2, 3, 4, 5]

Generators, yield

[131]:
l = [1, 2, 3]
[132]:
for elem in l:
    print(elem)
1
2
3
[133]:
it = iter(l)
[134]:
next(it)
[134]:
1
[135]:
next(it)
[135]:
2
[136]:
next(it)
[136]:
3
[137]:
try:
    next(it)
except StopIteration as e:
    print(e, type(e))
 <class 'StopIteration'>
[138]:
s = 'abc'
[139]:
for elem in s:
    print(elem)
a
b
c
[140]:
l = list()
[141]:
l
[141]:
[]
[142]:
l = list([1, 2, 3])
[143]:
l
[143]:
[1, 2, 3]
[144]:
l = [1, 2, 3]
[145]:
l = list(range(1, 4))
[146]:
l
[146]:
[1, 2, 3]
[147]:
for elem in range(4):
    print(elem)
0
1
2
3
[148]:
for elem in range(2, 4):
    print(elem)
2
3
[149]:
def my_funky_generator():
    print('bis zum ersten')
    yield 1
    print('bis zum zweiten')
    yield 2
    print('bis zum dritten')
    yield 3
    print('und aus')
[150]:
meine_dumme_sequenz = my_funky_generator()
[151]:
type(meine_dumme_sequenz)
[151]:
generator
[152]:
it = iter(meine_dumme_sequenz)
[153]:
next(it)
bis zum ersten
[153]:
1
[154]:
next(it)
bis zum zweiten
[154]:
2
[155]:
next(it)
bis zum dritten
[155]:
3
[156]:
try:
    next(it)
except StopIteration as e:
    print(e, type(e))
und aus
 <class 'StopIteration'>
[157]:
for elem in my_funky_generator():
    print(elem)
bis zum ersten
1
bis zum zweiten
2
bis zum dritten
3
und aus
[158]:
def my_range(end):
    cur = 0
    while cur < end:
        yield cur
        cur += 1
[159]:
for elem in my_range(4):
    print(elem)
0
1
2
3

Other -ables: Callable

[160]:
print('hallo')
hallo
[161]:
type(print)
[161]:
builtin_function_or_method
[162]:
type(list)
[162]:
type
[163]:
list()
[163]:
[]
[164]:
def f():
    print('hallo f()')
[165]:
f()
hallo f()
[166]:
type(f)
[166]:
function
[167]:
f.__call__
[167]:
<method-wrapper '__call__' of function object at 0x7fe9785083a0>
[168]:
f.__call__()
hallo f()
[169]:
list.__call__
[169]:
<method-wrapper '__call__' of type object at 0x7fe98c21bce0>
[170]:
list.__call__('abc')
[170]:
['a', 'b', 'c']
[171]:
list('abc')
[171]:
['a', 'b', 'c']
[172]:
class Greeter:
    def __call__(self, s):
        print('hallo', s)
[173]:
g = Greeter()
[174]:
type(g)
[174]:
__main__.Greeter
[175]:
g('Joerg')
hallo Joerg
[176]:
g.__call__
[176]:
<bound method Greeter.__call__ of <__main__.Greeter object at 0x7fe9796976d0>>
[177]:
g.__call__('Joerg')
hallo Joerg

Indexing and Slicing

[178]:
l = [1, 2, [3, 4, 5], 6, 7]
l[2]
[178]:
[3, 4, 5]
[179]:
l[2][1]
[179]:
4
[180]:
l[2:3] = l[2]
[181]:
l
[181]:
[1, 2, 3, 4, 5, 6, 7]

References, (Im)mutability

[182]:
a = 42
[183]:
id(a)
[183]:
140640823526928
[184]:
a += 1
[185]:
id(a)
[185]:
140640823526960
[186]:
t = (1, 'eins')
[187]:
id(t)
[187]:
140640740502720
[188]:
try:
    t.append(3)
except Exception as e:
    print(e, type(e))
'tuple' object has no attribute 'append' <class 'AttributeError'>
[189]:
t += (2, 'zwei')
[190]:
id(t)
[190]:
140640722823952
[191]:
t
[191]:
(1, 'eins', 2, 'zwei')
[192]:
l = [1, 2, 3]
[193]:
id(l)
[193]:
140640741119552
[194]:
l += [4, 5, 6]
[195]:
id(l)
[195]:
140640741119552
[196]:
l
[196]:
[1, 2, 3, 4, 5, 6]
[197]:
l_copy = l[:]
[198]:
l_copy
[198]:
[1, 2, 3, 4, 5, 6]
[199]:
id(l_copy)
[199]:
140640741312256
[200]:
l_copy is l
[200]:
False
[201]:
l1 = [1, [2, 3, 4], 5]
[202]:
l2 = l1[:]
[203]:
l2
[203]:
[1, [2, 3, 4], 5]
[204]:
l2 is not l1
[204]:
True
[205]:
l2[1].append(666)
[206]:
l2
[206]:
[1, [2, 3, 4, 666], 5]
[207]:
l1
[207]:
[1, [2, 3, 4, 666], 5]
[208]:
l1[1] is l2[1]
[208]:
True
[209]:
import copy
[210]:
l1
[210]:
[1, [2, 3, 4, 666], 5]
[211]:
id(l1)
[211]:
140640722734080
[212]:
id(l1[1])
[212]:
140640722760768
[213]:
l3 = copy.deepcopy(l1)
[214]:
id(l3)
[214]:
140640722739712
[215]:
id(l3[1])
[215]:
140640741402496

exec() (and eval())

[216]:
code = '''
b = 666
print('hallo')
'''
[217]:
exec(code)
hallo
[218]:
b
[218]:
666
[219]:
context = {}
exec(code, context)
hallo
[220]:
b
[220]:
666
[221]:
del b
[222]:
context['b']
[222]:
666

More About Strings

[223]:
"abc"
[223]:
'abc'
[224]:
'abc'
[224]:
'abc'
[225]:
'don\'t'
[225]:
"don't"
[226]:
"don't"
[226]:
"don't"

Raw Strings

[227]:
s = "C:\path\to\nowhere"
[228]:
print(s)
C:\path o
owhere
[229]:
s = r"C:\path\to\nowhere"
print(s)
C:\path\to\nowhere
[230]:
import re
[231]:
line = "   666 |    Joerg    |Faschingbauer   "
[232]:
regex = re.compile(r'^\s*(\d+)\s*|\s*([A-Za-z]+)\s*|\s*([A-Za-z]+)\s*$')
[233]:
match = regex.search(line)
[234]:
match.group(1)
[234]:
'666'

Formatting (f-Strings)

[235]:
a = 42
b = 666
[236]:
'a hat den Wert '+str(a)+', und b hat den Wert '+str(b)
[236]:
'a hat den Wert 42, und b hat den Wert 666'
[237]:
f'a hat den Wert {a:07}, und b hat den Wert {b}'
[237]:
'a hat den Wert 0000042, und b hat den Wert 666'

Miscellaneous String Methods

[238]:
s = '666'
[239]:
s.isdigit()
[239]:
True
[240]:
'abc'.isdigit()
[240]:
False
[241]:
'abc'.isalpha()
[241]:
True
[242]:
'abc'.isidentifier()
[242]:
True
[243]:
'666'.isidentifier()
[243]:
False
[244]:
'mississippi'.count('ss')
[244]:
2
[245]:
'file.csv'.endswith('.csv')
[245]:
True
[246]:
'mississippi'.find('ss')
[246]:
2
[247]:
'mississippi'.find('xx')
[247]:
-1
[248]:
'mississippi'.rfind('ss')
[248]:
5
[249]:
line = "   666 |    Joerg    |Faschingbauer   "
[250]:
line.split('|')
[250]:
['   666 ', '    Joerg    ', 'Faschingbauer   ']
[251]:
'   666        '.strip()
[251]:
'666'
[252]:
'   666        '.lstrip()
[252]:
'666        '
[253]:
'   666        '.rstrip()
[253]:
'   666'
[254]:
line = "   666 |    Joerg    |Faschingbauer   "
[255]:
[elem.strip() for elem in line.split('|')]
[255]:
['666', 'Joerg', 'Faschingbauer']
[256]:
elems = ['666', 'Joerg', 'Faschingbauer']
'|'.join(elems)
[256]:
'666|Joerg|Faschingbauer'
[257]:
line = "   666 |    Joerg    |Faschingbauer   "
[258]:
svnr, firstname, lastname = [elem.strip() for elem in line.split('|')]
[259]:
svnr, firstname, lastname
[259]:
('666', 'Joerg', 'Faschingbauer')

More About Lists

[260]:
l = [1, 2, 'drei']
[261]:
l.append(4.0)
[262]:
l
[262]:
[1, 2, 'drei', 4.0]
[263]:
l.extend([3, 4, 5])
[264]:
l
[264]:
[1, 2, 'drei', 4.0, 3, 4, 5]
[265]:
l.extend(range(10, 15))
[266]:
l
[266]:
[1, 2, 'drei', 4.0, 3, 4, 5, 10, 11, 12, 13, 14]
[267]:
l.extend('abc')
[268]:
l
[268]:
[1, 2, 'drei', 4.0, 3, 4, 5, 10, 11, 12, 13, 14, 'a', 'b', 'c']
[269]:
l.insert(3, 3.5)
[270]:
l
[270]:
[1, 2, 'drei', 3.5, 4.0, 3, 4, 5, 10, 11, 12, 13, 14, 'a', 'b', 'c']
[271]:
l.insert(0, -1)
[272]:
l
[272]:
[-1, 1, 2, 'drei', 3.5, 4.0, 3, 4, 5, 10, 11, 12, 13, 14, 'a', 'b', 'c']
[273]:
l.pop(3)
[273]:
'drei'
[274]:
del l[1]
[275]:
l = [45, 2, 3, 9, 1]
[276]:
l.sort()
[277]:
l
[277]:
[1, 2, 3, 9, 45]
[278]:
l = [45, 2, 3, 9, 1]
[279]:
sorted(l)
[279]:
[1, 2, 3, 9, 45]
[280]:
l
[280]:
[45, 2, 3, 9, 1]
[281]:
l.reverse()
[282]:
l
[282]:
[1, 9, 3, 2, 45]

More About Dictionaries

[283]:
d = {'one':1, 'two': 2}
d
[283]:
{'one': 1, 'two': 2}
[284]:
l = [('one',1), ('two', 2)]
d = dict(l)
[285]:
d
[285]:
{'one': 1, 'two': 2}
[286]:
d['three'] = 3
[287]:
d
[287]:
{'one': 1, 'two': 2, 'three': 3}
[288]:
d['three'] = 3.0
[289]:
d
[289]:
{'one': 1, 'two': 2, 'three': 3.0}
[290]:
del d['three']
[291]:
'three' in d
[291]:
False
[293]:
try:
    d['three']
except Exception as e:
    print(e, type(e))
'three' <class 'KeyError'>
[294]:
value = d.get('three')
if value is None:
    print('bled, aber, waere doch wohl', 3)
else:
    print('jo eh,', value)
bled, aber, waere doch wohl 3
[296]:
value = d.get('three', 3)
print(value)
3
[298]:
if 'three' in d:
    value = d['three']
else:
    value = 3
    d['three'] = value
print(value)
3
[299]:
del d['three']
[300]:
value = d.setdefault('three', 3)
print(value)
3
[301]:
d
[301]:
{'one': 1, 'two': 2, 'three': 3}
[302]:
other = {'three': 3.0, 'four': 4.0}
[303]:
d.update(other)
[305]:
d
[305]:
{'one': 1, 'two': 2, 'three': 3.0, 'four': 4.0}

More About Sets

[306]:
s = {1,2,3}
[307]:
l = [1, 2, 3]
[308]:
s = set(l)
[309]:
s
[309]:
{1, 2, 3}
[310]:
s = set('abc')
s
[310]:
{'a', 'b', 'c'}
[311]:
s = set(range(5))
s
[311]:
{0, 1, 2, 3, 4}
[312]:
2 in s
[312]:
True
[313]:
s.remove(2)
s
[313]:
{0, 1, 3, 4}
[314]:
s.add(2)
[315]:
s
[315]:
{0, 1, 2, 3, 4}
[320]:
s1 = set(range(4))
s2 = set(range(3, 8))
[321]:
s1, s2
[321]:
({0, 1, 2, 3}, {3, 4, 5, 6, 7})
[322]:
s1 | s2
[322]:
{0, 1, 2, 3, 4, 5, 6, 7}
[323]:
s1 & s2
[323]:
{3}
[324]:
s1 ^ s2
[324]:
{0, 1, 2, 4, 5, 6, 7}
[325]:
s1 < s2
[325]:
False
[326]:
s1 <= s2
[326]:
False

Encoding

[1]:
s = 'Liebe Grüße, Jörg'
[2]:
type(s)
[2]:
str
[4]:
try:
    s.encode(encoding='ascii')
except Exception as e:
    print(e, type(e))
'ascii' codec can't encode characters in position 8-9: ordinal not in range(128) <class 'UnicodeEncodeError'>
[7]:
b = s.encode(encoding='iso-8859-1')
[13]:
b
[13]:
b'Liebe Gr\xfc\xdfe, J\xf6rg'
[9]:
type(b)
[9]:
bytes
[10]:
b.decode(encoding='iso-8859-5')
[10]:
'Liebe Grќпe, Jіrg'
[11]:
print(b)
b'Liebe Gr\xfc\xdfe, J\xf6rg'
[14]:
lg = '祝好'
[16]:
type(lg)
[16]:
str
[17]:
len(lg)
[17]:
2
[20]:
lg.encode(encoding='big5')
[20]:
b'\xaf\xac\xa6n'
[21]:
len(lg.encode(encoding='big5'))
[21]:
4
[22]:
unterschrift = lg + ' Jörg'
[23]:
unterschrift
[23]:
'祝好 Jörg'
[25]:
try:
    unterschrift.encode('iso-8859-1')
except Exception as e:
    print(e, type(e))
'latin-1' codec can't encode characters in position 0-1: ordinal not in range(256) <class 'UnicodeEncodeError'>
[26]:
try:
    unterschrift.encode('big5')
except Exception as e:
    print(e, type(e))
'big5' codec can't encode character '\xf6' in position 4: illegal multibyte sequence <class 'UnicodeEncodeError'>
[27]:
unterschrift.encode('utf-8')
[27]:
b'\xe7\xa5\x9d\xe5\xa5\xbd J\xc3\xb6rg'
[28]:
unterschrift.encode('utf-16')
[28]:
b'\xff\xfe]y}Y \x00J\x00\xf6\x00r\x00g\x00'
[29]:
unterschrift.encode('utf-32')
[29]:
b'\xff\xfe\x00\x00]y\x00\x00}Y\x00\x00 \x00\x00\x00J\x00\x00\x00\xf6\x00\x00\x00r\x00\x00\x00g\x00\x00\x00'