This is a draft cheat sheet. It is a work in progress and is not finished yet.
základní funkce
print(x, y) |
x = input("zadej x: ") |
len(list), min(list), max(list) |
pozor: pro dict se dívá na keys(), ne values() |
sum(list) |
konverze datových typů
a, b, c = 1, "2", "tohle je string"
a + int(b) # součet: 3
str(a) + b # konkatenace: '12'
int(c) # ValueError
type(a) is int # True
lst = [a,b] + [c] # [1, "2", "tohle je string"]
|
|
|
kondicionály, funkce, docstring, assert, raise
def druha_mocnina(x):
"""
Funkce vrátí druhou mocninu kladného čísla.
Pokud vstup není int, funkce padne (assertion error).
Pokud je vstup záporné číslo, funkce padne (KeyError).
"""
assert isinstance(x,int), "x: není číslo"
if x < 0:
raise ValueError("funkce padne pro záporné číslo")
elif x < 10:
raise ValueError("v programu je bug")
else:
pass # nic nedělej
return x ** 2
|
try, except
try:
druha_mocnina(-1)
except ValueError as e:
print("Máme chybu", e)
# raise e # pokud chceme chybu propagovat dál
|
|
|
|