rain = True
if rain is True:
agenda = 'Stay Home'
agenda
'Stay Home'
def percentage(a, b):
if b == 0:
return None
return round(a/b, 2)
percentage(10, 100)
0.1
percentage(1, 0)
name = 'Adrian'
if name == 'Annie':
print('Hello Annie!')
else:
print("I don't know you...")
I don't know you...
if name in {'Adrian', 'Annie'}:
print('Hey, I know you!')
elif name in {'Agnus', 'Angela'}:
print("Hi! I thing we've met somewhere...")
elif name in {'Boris', 'Brunhilde'} :
# don't talk with them
pass # pass can be used in code when sintaxis requires some code, but none is needed
else:
print("I don't think I know you...")
Hey, I know you!
if
statements¶name = name or 'Sigizmund'
name
'Adrian'
name = 0
name = name or 'Sigizmund'
name
'Sigizmund'
name = 0
name = name if name is not None else 'Sigizmund'
name
0
if
in comprehensions¶characters = [
{'name': 'Peter', "surname": 'Rabbit'},
{'name': 'Josephine', 'surname': 'Rabbit'},
{'name': 'Michael', 'surname': 'McGregor'}
]
rabbits = [el['name'] for el in characters if el['surname'] == 'Rabbit']
rabbits
['Peter', 'Josephine']
For
loop¶for i in range(3):
print(i)
0 1 2
for char in 'Jack':
print(char)
J a c k
person = {
'name':'Jim',
'surname':'Hockins'
}
for k, v in person.items():
print(k, ':', v)
name : Jim surname : Hockins
from itertools import cycle
colors, categories = cycle(('red', 'green', 'blue')), (1, 2, 3, 4, 5)
for cat, color in zip(categories, colors):
print(cat, color)
1 red 2 green 3 blue 4 red 5 green
from itertools import groupby
characters = [
{'name': 'Peter', "surname": 'Rabbit'},
{'name': 'Josephine', 'surname': 'Rabbit'},
{'name': 'Michael', 'surname': 'McGregor'}
]
for group_name, group in groupby(characters, lambda x: x['surname']):
print(group_name)
for el in group:
print(' ', el['name'])
Rabbit Peter Josephine McGregor Michael
from itertools import product
w1, w2, w3, w4 = 'Hello the wonderful world!'.split() # splits by the whitespace by default
values1 = []
for el1 in w1:
for el2 in w2:
for el3 in w3:
for el4 in w4:
values1.append(el1 + el2 + el3 + el4)
# OR
values2 = []
for el1, el2, el3, el4 in product(w1, w2, w3, w4):
values2.append(el1 + el2 + el3 + el4)
values1 == values2
True
# here, 1 defines starting index
for i, (k, v) in enumerate(person.items(), 1):
print(f'{i}. {k}: {v}')
1. name: Jim 2. surname: Hockins
While
loop¶counter = 0
while counter < 5:
print(counter)
counter += 1
0 1 2 3 4
from random import randint # built-in random values generator
counter = 0
minimum = 10
while True:
value = randint(1, 100)
if value < minimum:
print('Below minimum!')
break
counter +=1
print(f'Value is: {value}, Samples took: {counter}')
Below minimum! Value is: 3, Samples took: 18
for letter in "Data":
if letter == 't':
break
print(letter)
D a
for letter in "Data":
if letter == 't':
continue
print(letter)
D a a
def _check_raise(inst, type_, text=None):
text = text if text is not None else f'Wrong value: requires {type} format, got {type(inst)}'
if not isinstance(inst, type_):
raise ValueError(text)
_check_raise('Hello', str)
_check_raise('Hello', int)
-------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-50-145b6e9f288c> in <module> ----> 1 _check_raise('Hello', int) <ipython-input-49-b95b042dc54b> in _check_raise(inst, type_, text) 3 4 if not isinstance(inst, type_): ----> 5 raise ValueError(text) ValueError: Wrong value: requires <class 'type'> format, got <class 'str'>
try:
result = 1 / 0
finally:
print('something is wrong!')
something is wrong!
-------------------------------------------------- ZeroDivisionErrorTraceback (most recent call last) <ipython-input-51-9d5a90f4a7ec> in <module> 1 try: ----> 2 result = 1 / 0 3 finally: 4 print('something is wrong!') ZeroDivisionError: division by zero
try:
result = 1 / 0
except ZeroDivisionError:
print('something is wrong!')
something is wrong!
import warnings
# built-in library that helps warning people - similar to exceptions, but won't halt code,
# you can also set up filter for different warning types
def percentage(value, total):
try:
return 100*(value / total)
except ZeroDivisionError:
warnings.warn('Total cannot be zero!')
except (TypeError, KeyError) as e:
# Keyerror here would never occur - just used it for example
warnings.warn(f'Something with the wrong: {e}')
except Exception as e:
raise Exception(value, total, e)
finally:
print('Anyhow, this function was executed!')
percentage(10, 0)
Anyhow, this function was executed!
/Users/philippk/anaconda3/envs/py36/lib/python3.6/site-packages/ipykernel_launcher.py:10: UserWarning: Total cannot be zero! # Remove the CWD from sys.path while we load stuff.
percentage('Hello', 'world')
Anyhow, this function was executed!
/Users/philippk/anaconda3/envs/py36/lib/python3.6/site-packages/ipykernel_launcher.py:14: UserWarning: Something with the wrong: unsupported operand type(s) for /: 'str' and 'str'
With
statement¶with open('./text_file.txt', 'r') as file:
data = file.read()
print(data)
Hello World!
try:
file = open('./text_file.txt', 'r').__enter__()
data = file.read()
finally:
file.__exit__()
data
'Hello\nWorld!'