python-control_flow-iterations-functions
python-control_flow-iterations-functions
2 Control Flow
[26]: x = inf
if x == 0:
print(x, "is zero")
elif x > 0:
print(x, "is positive")
elif x < 0:
print(x, "is negative")
else:
print(x, "is unlike anything I've ever seen...")
␣
,→---------------------------------------------------------------------------
<ipython-input-26-87def6aed850> in <module>
----> 1 x = inf
2
3 if x == 0:
1
4 print(x, "is zero")
5 elif x > 0:
[ ]: for N in range(5):
print(N, end=' ') # print all on same line
3 Functions
abc d e f g
2
abc--d--e--f--g
Input
a: a number
b: another number
[30]: add(1,1)
[30]: 2
Input
a: a number
b: another number
print_result: boolean, set to true if you'd like the result printed
Your result is 2
[32]: 2
3
3.2 Default Arguments
Input
a: a number
b: another number
print_result: boolean, set to true if you'd like the result printed
[34]: add_and_print(1, 1)
Your result is 2
[34]: 2
Input
a: a number
b: another number
print_result: boolean, set to true if you'd like the result printed
4
Your result is 3
[36]: 3
[37]: 42
[38]: 3
4 Classes
def is_adult(self):
return self.age > 18
print(p1.name)
print(p1.age)
print(p1.is_adult())
John
36
True
p2 = Student("Peter", 20)
5
p2.is_adult()
[41]: True
[42]: # the string representation of the Person class is not very informative
p1
5 List Comprehensions
A simple way of compressing a list building for loop into single statement
6
[45]: L = []
for n in range(12):
L.append(n ** 2)
L
[45]: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121]
[46]: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121]
6 Set Comprehensions
[48]: {0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121}
7 Dict Comprehensions
[49]: {0: 0,
1: 1,
2: 4,
3: 9,
4: 16,
5: 25,
6: 36,
7: 49,
8: 64,
9: 81,
7
10: 100,
11: 121}
8 Generator Comprehensions
[51]: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121]
9 Iterators
1
2
␣
---------------------------------------------------------------------------
,→
<ipython-input-52-bdcbfa3d0082> in <module>
2 print(next(my_iterator))
3 print(next(my_iterator))
----> 4 print(next(my_iterator))
8
StopIteration:
def __next__(self):
if self.start >= self.stop:
raise StopIteration
current = self.start * self.start
self.start += 1
return current
iterator = Squares(1, 5)
[i for i in iterator]
9.2.1 enumerate
Often you need not only the elements of a collection but also their index
[54]: L = [2, 4, 6]
for i in range(len(L)):
print(i, L[i])
0 2
1 4
2 6
Instead you can write
[55]: L = [2, 4, 6]
for idx, element in enumerate(L):
print(idx, element)
9
0 2
1 4
2 6
9.2.2 zip
2 3
4 5
6 7
8 9
10 11
('a', 'b')
(1, 2)
9.2.4 map
0
1
4
9
16
10
9.2.5 filter
0
4
16
0 4 16
9.3.1 Permutations
9.3.2 Combinations
9.3.3 Product
11
[63]: from itertools import product
my_iterator = range(3)
another_iterator = iter(['a', 'b'])
yet_another_iterator = iter([True, False])
p = product(my_iterator, another_iterator, yet_another_iterator)
print(*p)
(0, 'a', True) (0, 'a', False) (0, 'b', True) (0, 'b', False) (1, 'a', True) (1,
'a', False) (1, 'b', True) (1, 'b', False) (2, 'a', True) (2, 'a', False) (2,
'b', True) (2, 'b', False)
9.3.4 Chaining
0 1 2 a b True False
Turning a nested collection like [['a','b'],'c'] into a flat one like ['a','b','c'] is called
flattening
[65]: from itertools import chain
my_nested_list = [['a','b'],'c']
p = chain(*my_nested_list)
print(*p)
a b c
12
generator = squares(1, 10)
[i for i in generator]
12 Errors
␣
,→---------------------------------------------------------------------------
<ipython-input-67-7ba079dc2063> in <module>
1 # Q was never defined
----> 2 print(Q)
13
NameError: name 'Q' is not defined
[76]: 1 + 'abc'
␣
,→---------------------------------------------------------------------------
<ipython-input-76-a51a3635a212> in <module>
----> 1 1 + 'abc'
[ ]: L = [1, 2, 3]
L[1000]
[ ]: 2 / 0
[77]: try:
print("this gets executed first")
except:
print("this gets executed only if there is an error")
[78]: try:
print("let's try something:")
x = 1 / 0 # ZeroDivisionError
except:
14
print("something bad happened!")
0.5
1e+100
[81]: 1e+100
␣
,→---------------------------------------------------------------------------
15
<ipython-input-83-cbb3eb91a66d> in <module>
----> 1 safe_divide(1, '2')
<ipython-input-82-57f0d324952e> in safe_divide(a, b)
1 def safe_divide(a, b):
2 try:
----> 3 return a / b
4 except ZeroDivisionError:
5 return 1E100
• When your code is executed, make sure that it’s clear what went wrong in case of errors.
• Throw specific errors built into Python
• Write your own error classes
[84]: raise RuntimeError("my error message")
␣
---------------------------------------------------------------------------
,→
<ipython-input-84-b1834d213d3b> in <module>
----> 1 raise RuntimeError("my error message")
16
[ ]: safe_divide(1, '2')
/Users/felix/anaconda3/envs/pdds_1920/lib/python3.7/site-
packages/ipykernel_launcher.py:10: UserWarning: Caught Error <class
'ZeroDivisionError'> with message float division by zero - will just return a
large number instead
# Remove the CWD from sys.path while we load stuff.
[86]: 1e+100
17
Let’s assume we have a file mymodule.py in the current working directory with the content:
mystring = 'hello world'
def myfunc():
print(mystring)
[88]: mymodule.myfunc()
hello world
[89]: -1.0
For longer module names, it’s not convenient to use the full module name.
[90]: import numpy as np
np.cos(np.pi)
[90]: -1.0
[91]: -1.0
18
13.5 Implicit import of module contents
You can import all elements of a module into the global namespace. Use with caution.
[92]: cos = 0
from math import *
sin(pi) ** 2 + cos(pi) ** 2
[92]: 1.0
Often, like when opening files, you want to make sure that the file handle gets closed in any case.
file = open(path, 'w')
try:
# an error
1 / 0
finally:
file.close()
Context managers are a convenient shortcut:
19
with open(path, 'w') as opened_file:
# an error
1/0
[96]: 'Eichhö'
␣
,→---------------------------------------------------------------------------
<ipython-input-98-9981ac9de387> in <module>
1 # byte representation
----> 2 data.decode('utf8')
20
[99]: # decoding error, utf-8 has variable length character encodings
data[:4].decode('utf8')
[99]: 'Eich'
21