Kurzy programovacího jazyka Python
kurzy.python@centrum.czhttps://github.com/tisnik/python-programming-courses- https://docs.python.org/3/library/idle.html
- vytvořeno přímo v Pythonu
- používá `tkinter`
- využitelné na Windows, Linuxu i macOS
- editor zdrojových kódů
- debugger
- Python shell (REPL)
2to3 pro automatický převod
print: příkaz vs funkcexrange(): nyní se range() chová jako xrange()except TypVýjimky, e: versus except TypVýjimky as e:next(), namísto ní se používá funkce next()range() vrací iterátor, ne seznamapply() byly přesunuty do zvláštního modulun = 10000
def test_range(n):
for i in range(n):
pass
def test_xrange(n):
for i in xrange(n):
pass
test_range(n)
test_xrange(n)
# Body Mass Index calculator
print("Mass (kg): ")
mass = int(input())
print("Height (cm): ")
height = int(input())
height = height / 100.0
bmi = mass / (height * height)
print("BMI = ", bmi)
python bmi.py
python2 bmi.py
python3 bmi.py
print()
input()
raw_input()
input())input("zprava")
print "Hello"
print("Hello")
print jako funkce
#!/usr/bin/env python
# encoding=utf-8
"""Dokumentační řetězec"""
# importy
# třídy
# funkce
if __name__ == "__main__":
# vstupní bod programu
#!/usr/bin/env python
# encoding=utf-8
"""Body Mass Index calculator."""
import sys
def compute_bmi(mass, height):
height = height / 100.0
bmi = mass / (height * height)
return bmi
print("Mass (kg): ")
mass = int(input())
if mass < 0:
print("Invalid input")
sys.exit(1)
print("Height (cm): ")
height = int(input())
if height < 0:
print("Invalid input")
sys.exit(1)
print("BMI = ", compute_bmi(mass, height))
chmod u+x bmi.py
./bmi.py
python bmi.py
python2 bmi.py
python3 bmi.py
and del from not while
as elif global or with
assert else if pass yield
break except import print
class exec in raise
continue finally is return
def for lambda try
Udržují informaci o stavu aplikace
x = 42
y = "Python"
z = 3e27
print(x)
print(y)
print(z)
x = None
print(x)
x = 10
print(x)
x = "něco jiného"
print(x)
42
Python
3e+27
None
10
něco jiného
int / long (Python 2.x / Python 3.x)floatcomplexprint(42)
print(3.1415)
print(2+3j)
/ (viz další slajdy s popisem operátorů)boolTrueFalseandornot==!=<<=>>=isis notinnot in# běžný řetězec
print("Hello")
# bytové pole
print(b"abcdef")
# podpora pro Unicode
print(u"příliš žluťoučký kůň")
# řídicí znaky
print("abc\ndef")
# 'raw' řetězce
print(r"abc\ndef")
# víceřádkový řetězec
print("""A
B
C
D
E
F""")
len - vrací počet znaků řetězcelen - vrací délku seznamuclearappendinsertcountreversesortseznam = [1, 2, 3, 4]
print(seznam[0])
print(seznam[1])
print(seznam[-1])
print(seznam[-2])
seznam.append(5)
seznam.append(6)
print(seznam)
del seznam[0]
print(seznam)
del seznam[-1]
print(seznam)
1
2
4
3
[1, 2, 3, 4, 5, 6]
[2, 3, 4, 5, 6]
[2, 3, 4, 5]
seznam1 = [1, 2, 3]
seznam2 = [4, 5, 6]
seznam3 = seznam1 + seznam2
print(seznam3)
[1, 2, 3, 4, 5, 6]
seznam1 = [1, 2, 3]
seznam2 = seznam1 * 3
print(seznam2)
[1, 2, 3, 1, 2, 3, 1, 2, 3]
seznam = [5, 4, 1, 3, 4, 100, -1]
print(seznam)
seznam.sort()
print(seznam)
seznam = [5, 4, 1, 3, 4, 100, -1]
print(seznam)
seznam2 = sorted(seznam)
print(seznam)
print(seznam2)
[5, 4, 1, 3, 4, 100, -1]
[-1, 1, 3, 4, 4, 5, 100]
[5, 4, 1, 3, 4, 100, -1]
[5, 4, 1, 3, 4, 100, -1]
[-1, 1, 3, 4, 4, 5, 100]
seznam = [1, 2, 3, 4, 5, 6]
print(seznam[2:4])
print(seznam[0:6:2])
print(seznam[4:1])
print(seznam[4:1:-1])
print(seznam[4:])
print(seznam[:4])
print(seznam[:])
[3, 4]
[1, 3, 5]
[]
[5, 4, 3]
[5, 6]
[1, 2, 3, 4]
[1, 2, 3, 4, 5, 6]
deld = {"id": 1,
"name": "Eda",
"surname": "Wasserfall"}
print(d)
print(d["name"])
d["hra"] = "Svestka"
print(d)
del d["id"]
print(d)
{'id': 1, 'name': 'Eda', 'surname': 'Wasserfall'}
Eda
{'id': 1, 'name': 'Eda', 'surname': 'Wasserfall', 'hra': 'Svestka'}
{'name': 'Eda', 'surname': 'Wasserfall', 'hra': 'Svestka'}
len - vrací počet prvků množinys = {1, 2, 3, 4}
print(s)
s2 = {"hello", "world", "!", 0}
print(s2)
s3 = set()
print(s3)
s3.add(1)
s3.add(2)
print(s3)
s3.update([3, 4, 5])
print(s3)
{1, 2, 3, 4}
{0, 'hello', 'world', '!'}
set()
{1, 2}
{1, 2, 3, 4, 5}
discard a removes1 = {1,2,3,4}
print(s1)
s1.discard(2)
print(s1)
s1.discard(1000)
print(s1)
s1.remove(3)
print(s1)
s1.remove(1000)
print(s1)
{1, 2, 3, 4}
{1, 3, 4}
{1, 3, 4}
{1, 4}
Traceback (most recent call last):
File "set_discard_remove.py", line 13, in <module>
s1.remove(1000)
KeyError: 1000
x in s
-test na existenci prvku v množiněx not in s
s <= t
s >= t
s | t
s & t
s - t
s ^ t
s1 = {1, 2, 3, 4}
s2 = {3, 4, 5, 6}
print(s1)
print(s2)
print(s1 | s2)
print(s1 & s2)
print(s1 - s2)
print(s2 - s1)
print(s1 ^ s2)
print(1 in s1)
print(10 in s1)
{1, 2, 3, 4}
{3, 4, 5, 6}
{1, 2, 3, 4, 5, 6}
{3, 4}
{1, 2}
{5, 6}
{1, 2, 5, 6}
True
False
s.issubset(t)
s.issuperset(t)
s.union(t)
s.intersection(t)
s.difference(t)
s.symmetric_difference(t)
engineers = {'John', 'Jane', 'Jack', 'Janice'}
programmers = {'Jack', 'Sam', 'Susan', 'Janice'}
managers = {'Jane', 'Jack', 'Susan', 'Zack'}
employees = engineers | programmers | managers
engineering_management = engineers & managers
fulltime_management = managers - engineers - programmers
print(engineers)
print(programmers)
print(managers)
print(employees)
print(engineering_management)
print(fulltime_management)
{'Jane', 'Jack', 'John', 'Janice'}
{'Sam', 'Jack', 'Susan', 'Janice'}
{'Zack', 'Susan', 'Jack', 'Jane'}
{'Jack', 'Zack', 'Susan', 'John', 'Sam', 'Jane', 'Janice'}
{'Jack', 'Jane'}
{'Zack'}
# tříprvková n-tice
t1 = (1, 2, 3)
# jednoprvková n-tice
t2 = (4, )
# pozor - není tuple!
t3 = (5)
# nehomogenní n-tice
t4 = (4, 3.14, "string", [])
# prázdná n-tice
t5 = ()
print(t1)
print(t2)
print(t3)
print(t4)
print(t5)
(1, 2, 3)
(4,)
5
(4, 3.14, 'string', [])
()
+x = (1, 2, 3)
y = (3, 4, 5)
print(x + y)
print(y + x)
(1, 2, 3, 3, 4, 5)
(3, 4, 5, 1, 2, 3)
x = (1, 2, 3)
y = (3, 4, 5)
z = x + y
print(1 in z)
print(10 in z)
print("foobar" in z)
True
False
False
+-*///%**==!=<> (jen v Pythonu 2.x, nyní již není podporován)><>=<=andornot&|^~<<>>=+=-=*=/=%=**=//=innot inisis notx = 1 if y > 10 else 0
x = 10
y = 3
print(x + y)
print(x - y)
print(x * y)
print(x / y)
print(x // y)
print(x % y)
print(x ** y)
13
7
30
3
3
1
1000
13
7
30
3.3333333333333335
3
1
1000
float/doublex = 10.0
y = 3
print(x + y)
print(x - y)
print(x * y)
print(x / y)
print(x // y)
print(x % y)
print(x ** y)
13.0
7.0
30.0
3.33333333333
3.0
1.0
1000.0
13.0
7.0
30.0
3.3333333333333335
3.0
1.0
1000.0
1 **
2 ~ + -
3 * / % //
4 + -
5 >> <<
6 &
7 ^ |
8 <= < > >=
9 <> == !=
10 = %= /= //= -= += *= **=
11 is is not
12 in not in
13 not or and
print '3 / 2 =', 3 / 2
print '3 // 2 =', 3 // 2
print '3 / 2.0 =', 3 / 2.0
print '3 // 2.0 =', 3 // 2.0
3 / 2 = 1
3 // 2 = 1
3 / 2.0 = 1.5
3 // 2.0 = 1.0
print('3 / 2 =', 3 / 2)
print('3 // 2 =', 3 // 2)
print('3 / 2.0 =', 3 / 2.0)
print('3 // 2.0 =', 3 // 2.0)
3 / 2 = 1.5
3 // 2 = 1
3 / 2.0 = 1.5
3 // 2.0 = 1.0
if condition1:
pass
print("Mass (kg): ")
mass = int(input())
if mass < 0:
print("Invalid input")
sys.exit(1)
if condition1:
pass
else:
pass
switch-caseif condition1:
pass
elif condition2:
pass
elif condition3:
pass
else:
pass
while-do – cyklus s podmínkou na začátkudo-while – cyklus s podmínkou na koncifor - unifikované while-dofor-each - průchod sekvencemiwhile-do – (zahrnuje i nekonečný cyklus)for-each - průchod sekvencemibreak a continue pro další variantywhilex = 1
while x < 2000:
print(x)
x *= 2
1
2
4
8
16
32
64
128
256
512
1024
forlist = ["one", "two", "three", "four"]
for item in list:
print(item)
one
two
three
four
forfor i in range(10):
print(i)
0
1
2
3
4
5
6
7
8
9
for i in range(4, 11, 2):
print(i)
4
6
8
10
for i in range(10, 0, -1):
print(i)
10
9
8
7
6
5
4
3
2
1
breakx = 1
while True:
print(x)
if x > 1000:
break
x *= 2
continuex = 1
while True:
if x > 1000:
break
x *= 2
if x < 100:
continue
print(x)
def compute_bmi(mass, height):
height = height / 100.0
bmi = mass / (height * height)
return bmi
def factorial(n):
return 1 if n <= 1 else n * factorial(n - 1)
print(factorial(10))
for n in range(1, 11):
print(n, factorial(n))
def factorial(n):
"""Výpočet faktoriálu ve smyčce."""
f = 1
for x in range(1, n + 1):
f *= x
return f
return může být v kódu umístěn kdekolicalls = 0
def ackermann(m, n):
global calls
calls += 1
if m == 0:
return n + 1
elif n == 0:
return ackermann(m - 1, 1)
else:
return ackermann(m - 1, ackermann(m, n - 1))
print(ackermann(3,4))
def fn1(arg1, arg2, arg3):
pass
def fn2(arg1, arg2, arg3=True):
pass
def fn3(arg1, arg2, *args):
pass
def fn4(arg1, arg2, **kwargs):
pass
globalnonlocalx = 1
def fn1():
pass
def fn2():
x = 2
def fn3():
global x
x = 3
print(x)
fn1()
print(x)
fn2()
print(x)
fn3()
print(x)
x = 0
def fn1():
x = 1
def fn2():
x = 2
print(x)
fn2()
print(x)
print(x)
fn1()
print(x)
x = 0
def fn1():
x = 1
def fn2():
nonlocal x
x = 2
print(x)
fn2()
print(x)
print(x)
fn1()
print(x)
x = 0
def fn1():
x = 1
def fn2():
global x
x = 2
print(x)
fn2()
print(x)
print(x)
fn1()
print(x)
x = 0
def fn1():
global x
x = 1
def fn2():
global x
x = 2
print(x)
fn2()
print(x)
print(x)
fn1()
print(x)
f = lambda x, y : x + y
print(f(1,2))
seznam = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
seznam2 = [item*2 for item in seznam]
seznam3 = [item for item in seznam if item % 3 == 0]
print(seznam)
print(seznam2)
print(seznam3)
mapx = range(10)
print(x)
y=map(lambda value: value*2, x)
print(list(y))
filterx = range(20)
print(x)
y = filter(lambda value: value % 3 == 0, x)
print(list(y))
reduce
functoolsfrom functools import reduce
x = range(1, 11)
print(x)
y = reduce(lambda a, b: a*b, x)
print(y)
openclosereadwriteappendfin = open("test.txt","r")
print(fin.read())
fin = open("test.txt", "r")
print(fin.readline())
fin = open("test.txt.", "r")
print(fin.readlines())
fout = open("hello.txt", "w")
fout.write("Hello World")
fout.close()
withwith open("test.txt") as fin:
print(fin.readline())
Metoda string.format()
Příklad použiti
print("hodnota: {value:5d}".format(value=42))
print("hodnota: {value:05d}".format(value=42))
for x in range(1, 11):
y = 1.0/x
print("1/{x:2d} = {y:5.3f}".format(x=x, y=y))
for x in range(1, 11):
y = 1.0/x
print("1/{x:02d} = {y:5.3f}".format(x=x, y=y))
for x in range(1, 11):
y = 1.0/x
print("1/{x:<2d} = {y:5.3f}".format(x=x, y=y))
finallyerrno)#!/usr/bin/python
try:
file = open("testfile", "w")
file.write("test")
except IOError:
print("soubor nelze otevrit pro zapis")
else:
print("zapis uspesne proveden")
file.close()
def function(level):
if level < 1:
raise ValueError("Invalid level!", level)
print("ok - function was called with parameter level set to {level}".format(level=level))
try:
for i in range(10, -10, -1):
function(i)
except ValueError as value:
print("Exception in function(): {value}".format(value=value))
else:
print("Everything is OK")
class B(Exception):
pass
class C(B):
pass
class D(C):
pass
for cls in [B, C, D]:
try:
raise cls()
except D:
print("D")
except C:
print("C")
except B:
print("B")
finally#!/usr/bin/python
try:
file = open("testfile", "w")
file.write("test")
except IOError:
print("soubor nelze otevrit pro zapis")
else:
print("zapis uspesne proveden")
finally:
file.close()
class Employee:
pass
e = Employee()
class Employee:
pass
e1 = Employee()
e2 = Employee()
selfJménoTřídy.jménoAtributuclass CLS:
x = 10
c1 = CLS()
print(CLS.x)
print(c1.x)
c1.x = 20
print(CLS.x)
print(c1.x)
class Employee:
def __init__(self, first_name, surname, salary):
self._first_name = first_name
self._surname = surname
self._salary = salary
e = Employee()
self def display_employee(self):
print("Full name: ", self._first_name, self._surname, " Salary: ", self._salary)
class A:
pass
class B(A):
pass
__init__
__str__
__repr__
__hash__
__call__
__iter__
__getattr__
__getattribute__
__setattr__
__delattr__
__eq__ x, y x == y
__ne__ x, y x != y
__lt__ x, y x < y
__gt__ x, y x > y
__le__ x, y x <= y
__ge__ x, y x >= y
__add__ binární + operátor
__sub__ binární - operátor
__mul__ * operátor
__div__ / operátor
__floordiv__ // operátor (P2)
__truediv__ / operátor (P3)
__mod__ % operátor
__pow__ ** operátor or pow(x, y, z)
__neg__ unární - operátor
__pos__ unární + operátor
__abs__ absolutní hodnota
__nonzero__ konverze na Boolean
__invert__ ~ operátor
__lshift__ << operátor
__rshift__ >> operátor
__and__ & operátor
__or__ x, y | operátor
__xor__ ^ operátor
__iadd__ += operátor
__isub__ -= operátor
__imul__ *= operátor
__idiv__ /= operátor (P2)
__ifloordiv__ //= operátor
__itruediv__ /= operátor (P3)
__imod__ %= operátor
__ipow__ **= operátor
__ilshift__ <<= operátor
__irshift__ >>= operátor
__iand__ &= operátor
__ior__ |= operátor
__ixor__ ^= operátor
class Employee:
def __init__(self, first_name, surname, salary):
self._first_name = first_name
self._surname = surname
self._salary = salary
def display_employee(self):
print("Full name: ", self._first_name, self._surname, " Salary: ", self._salary)
class Employee:
def __init__(self, first_name, surname, salary):
self._first_name = first_name
self._surname = surname
self._salary = salary
def display_employee(self):
print("Full name: {name} {surname} Salary: {salary}".format(name=self._first_name,
surname=self._surname,
salary=self._salary))
employee1 = Employee("Eda", "Wasserfall", 10000)
employee2 = Employee("Přemysl", "Hájek", 25001)
employee1.display_employee()
employee2.display_employee()
class Employee:
def __init__(self, first_name, surname, salary):
self._first_name = first_name
self._surname = surname
self._salary = salary
def __str__(self):
return "Full name: {name} {surname} Salary: {salary}".format(name=self._first_name,
surname=self._surname,
salary=self._salary)
employee1 = Employee("Eda", "Wasserfall", 10000)
employee2 = Employee("Přemysl", "Hájek", 25001)
print(employee1)
print(employee2)
python -m pdb test.py
pdb.set_trace()
try:
raise Exception()
except:
import pdb
pdb.post_mortem()
from machine import Pin
pin = Pin(0, Pin.IN)
print(pin.value())
from machine import Pin
pin = Pin(14, Pin.OUT)
pin.value(1)