Jazyk Python - základy programování

Kurzy programovacího jazyka Python

Jazyk Python - základy programování


Obsah kurzu (1/3)


Obsah kurzu (2/3)


Obsah kurzu (3/3)


Úvod


Základní informace o jazyku Python


Interpretry vs překladače


Proč a k čemu používat programovací jazyk Python


Vývojová prostředí pro Python


IDLE

- 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)

Srovnání s ostatními programovacími jazyky


Implementace Pythonu


Python pro Windows


Python 2.x vs Python 3.x


Python 2.x vs Python 3.x: range/xrange

n = 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)

Základy programovacího jazyka Python


Python jako skriptovací jazyk

# 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 jako skriptovací jazyk

python bmi.py
python2 bmi.py
python3 bmi.py

Základní vstupně/výstupní funkce


Funkce print

print "Hello"
print("Hello")

Funkce print


Základní struktura kódu v Pythonu

#!/usr/bin/env python
# encoding=utf-8

"""Dokumentační řetězec"""

# importy
# třídy
# funkce

if __name__ == "__main__":
    # vstupní bod programu

Ukázkový příklad - úprava kalkulátoru BMI

#!/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))

Ukázkový příklad (pokračování)

chmod u+x bmi.py
./bmi.py
python bmi.py
python2 bmi.py
python3 bmi.py

Rezervovaná klíčová slova Pythonu

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

Proměnné


Příklad použití proměnných

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

Datové typy


Měnitelnost/neměnitelnost


Homogennost


Čísla

print(42)
print(3.1415)
print(2+3j)

Pravdivostní hodnoty


Pravdivostní hodnoty


Řetězce (raw, Unicode)


Řetězce (raw, Unicode)

# 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""")

Funkce pro práci s řetězci


Seznamy (pole)


Funkce pro práci se seznamy


Metody pro práci se seznamy


Seznamy (pole) - ukázka

seznam = [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]

Operace spojení seznamů

seznam1 = [1, 2, 3]
seznam2 = [4, 5, 6]

seznam3 = seznam1 + seznam2

print(seznam3)
[1, 2, 3, 4, 5, 6]

Operace opakování seznamu

seznam1 = [1, 2, 3]

seznam2 = seznam1 * 3
print(seznam2)
[1, 2, 3, 1, 2, 3, 1, 2, 3]

Seřazení seznamu

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]

Vytvoření podseznamu

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]

Slovníky


Slovníky - ukázka

d = {"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'}

Množiny


Funkce pro práci s množinami


Množiny

s = {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}

Operace discard a remove

s1 = {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

Množinové operace


Množinové operace - příklad použití

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

Zápis množinových operací metodami

s.issubset(t)
s.issuperset(t)
s.union(t)
s.intersection(t)
s.difference(t)
s.symmetric_difference(t)

Množinové operace - příklad použití

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'}

N-tice


# 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', [])
()

Spojení n-tic operátorem +

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)

Test na existenci prvku v n-tici

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

Výrazy, operátory


Výrazy, operátory


Výrazy, operátory


Výrazy, operátory


Výrazy, operátory


Výrazy, operátory


Rozhodovací konstrukce ve výrazu

x = 1 if y > 10 else 0

Výrazy, operátory: ukázky použití

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

Výrazy, operátory: ukázky použití

x = 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

Priority operátorů

1       **
2       ~ + -
3       * / % //
4       + -
5       >> <<
6       &
7       ^ |
8       <= < > >=
9       <> == !=
10      = %= /= //= -= += *= **=
11      is   is not
12      in   not in
13      not or and

Celočíselné dělení

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

Řízení toku programu


Základní pojmy


Větvení (rozhodovací konstrukce)

if condition1:
    pass
print("Mass (kg): ")
mass = int(input())

if mass < 0:
    print("Invalid input")
    sys.exit(1)

Složitější formy větvení

if condition1:
    pass
else:
    pass

Složitější formy větvení

if condition1:
    pass
elif condition2:
    pass
elif condition3:
    pass
else:
    pass

Programové smyčky


Programová smyčka while

x = 1

while x < 2000:
    print(x)
    x *= 2
1
2
4
8
16
32
64
128
256
512
1024

Programová smyčka for

list = ["one", "two", "three", "four"]

for item in list:
    print(item)
one
two
three
four

Typická podoba for

for 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

Konstrukce break

x = 1

while True:
    print(x)
    if x > 1000:
        break
    x *= 2

Konstrukce continue

x = 1

while True:
    if x > 1000:
        break
    x *= 2
    if x < 100:
        continue
    print(x)


Procedury a funkce


Základní pojmy


Příklady použití


Běžná funkce

def compute_bmi(mass, height):
    height = height / 100.0
    bmi = mass / (height * height)
    return bmi

Rekurzivní funkce

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

Složitější rekurzivní funkce

calls = 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))

Definice funkcí

def fn1(arg1, arg2, arg3):
    pass
def fn2(arg1, arg2, arg3=True):
    pass

Definice funkcí

def fn3(arg1, arg2, *args):
    pass
def fn4(arg1, arg2, **kwargs):
    pass

Oblast platnosti proměnných

x = 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)

Význam global/nonlocal

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)

Funkcionální prvky jazyka


Lambda výrazy

f = lambda x, y : x + y
print(f(1,2))

Generátorová notace seznamu

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)

Funkce vyššího řádu

x = range(10)

print(x)

y=map(lambda value: value*2, x)
print(list(y))
x = range(20)

print(x)

y = filter(lambda value: value % 3 == 0, x)
print(list(y))
from functools import reduce

x = range(1, 11)

print(x)

y = reduce(lambda a, b: a*b, x)
print(y)

Moduly


Vstup a výstup


Práce se soubory


Souborové objekty

fin = 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()

Použití bloku with

with open("test.txt") as fin:
    print(fin.readline())

Formátování výstupu

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))

Chyby a výjimky


Důvody vedoucí k zavedení výjimek


Důvody vedoucí k zavedení výjimek


Zachycení výjimky

#!/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()

Vyvolání výjimky

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")

Vlastní výjimky

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")

Blok 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()

Třídy


Použitá terminologie


Definice třídy

class Employee:
    pass

e = Employee()

Objekty

class Employee:
    pass

e1 = Employee()
e2 = Employee()

Atributy

class CLS:
    x = 10

c1 = CLS()
print(CLS.x)
print(c1.x)

c1.x = 20
print(CLS.x)
print(c1.x)

Konstruktor

class Employee:

    def __init__(self, first_name, surname, salary):
        self._first_name = first_name
        self._surname = surname
        self._salary = salary

e = Employee()

Metody

    def display_employee(self):
        print("Full name: ", self._first_name, self._surname, "   Salary: ", self._salary)

Dědičnost

class A:
    pass

class B(A):
    pass

Speciální metody

__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

Definice třídy

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()

Přetížení speciální metody __str__

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)

Úprava příkazového řádku


Použití debuggeru

python -m pdb test.py
pdb.set_trace()

Post mortem debug

try:
    raise Exception()
except:
    import pdb
    pdb.post_mortem()

MicroPython


MicroPython


Rozdíly CPython vs MicroPython

from machine import Pin
pin = Pin(0, Pin.IN)
print(pin.value())
from machine import Pin
pin = Pin(14, Pin.OUT)
pin.value(1)

MicroPython pro MicroBit


Užitečné nástroje pro Python


Užitečné odkazy