Numbers

In [4]:
# Potęgowanie...
a = 2**10
print(a)
1024
In [5]:
2**63
Out[5]:
9223372036854775808
In [6]:
2**128
Out[6]:
340282366920938463463374607431768211456
In [7]:
2**4000
Out[7]:
13182040934309431001038897942365913631840191610932727690928034502417569281128344551079752123172122033140940756480716823038446817694240581281731062452512184038544674444386888956328970642771993930036586552924249514488832183389415832375620009284922608946111038578754077913265440918583125586050431647284603636490823850007826811672468900210689104488089485347192152708820119765006125944858397761874669301278745233504796586994514054435217053803732703240283400815926169348364799472716094576894007243168662568886603065832486830606125017643356469732407252874567217733694824236675323341755681839221954693820456072020253884371226826844858636194212875139566587445390068014747975813971748114770439248826688667129237954128555841874460665729630492658600179338272579110020881228767361200603478973120168893997574353727653998969223092798255701666067972698906236921628764772837915526086464389161570534616956703744840502975279094087587298968423516531626090898389351449020056851221079048966718878943309232071978575639877208621237040940126912767610658141079378758043403611425454744180577150855204937163460902512732551260539639221457005977247266676344018155647509515396711351487546062479444592779055555421362722504575706910949376
In [8]:
a = len(str(2**4000))
a
Out[8]:
1205
In [9]:
1.0 / 10 == 0.1
Out[9]:
True
In [10]:
0.1 == 0.10000000000000001
Out[10]:
True

Data types

Lists

In [11]:
arr = [0,1,2,3]
print(arr)
[0, 1, 2, 3]
In [12]:
# Listy w pythonie są bardzo elastyczne
arr = [1,2,'cos', [10,11,12], 3.14]
print(arr)
[1, 2, 'cos', [10, 11, 12], 3.14]
In [13]:
arr = [0,1,2,3]
print(arr)
[0, 1, 2, 3]
In [14]:
len(arr)
Out[14]:
4
In [16]:
# Wartość której komórki zostanie odczytana?
arr[1]
Out[16]:
1
In [17]:
# Elementy listy można łatwo nadpisać
arr[2] = 2
arr[2]
Out[17]:
2
In [18]:
arr[1] = 1
In [15]:
# Czy to zadziała?
arr[-1]
Out[15]:
3
In [19]:
# Wartości których komórek zostaną odczytane?
arr[1:3]
Out[19]:
[1, 2]
In [21]:
arr[:3]
Out[21]:
[0, 1, 2]
In [22]:
arr[-2:]
Out[22]:
[2, 3]
In [23]:
arr[-3:-1]
Out[23]:
[1, 2]
In [24]:
arr = [0,1,2,3,4,5,6]
arr[0:5]
Out[24]:
[0, 1, 2, 3, 4]
In [25]:
arr[0:5:2]
Out[25]:
[0, 2, 4]
In [26]:
arr[::2]
Out[26]:
[0, 2, 4, 6]
In [27]:
arr[::-1]
Out[27]:
[6, 5, 4, 3, 2, 1, 0]
In [28]:
# Konkatenacja
a=[0,1,2,3]
b=['a','b','c','d']
a+b
Out[28]:
[0, 1, 2, 3, 'a', 'b', 'c', 'd']
In [30]:
# Dodawanie do listy
a=[10,20,30,40]
a.append(100)
a
Out[30]:
[10, 20, 30, 40, 100]
In [31]:
# Usuwanie z listy
a=[10,20,20,30,40]
a.remove(20)
a.pop(3)
a
Out[31]:
[10, 20, 30]
In [32]:
# Python ma wiele fajnych funkcji, np.
a = [4, 6, 'd','y', 3 ,6]
'd' in a
Out[32]:
True
In [33]:
a.index('d')
Out[33]:
2

Tuples

In [34]:
# Czym się różni tuple od listy? (Poza nawiasami)
a = (1,2,3)
a
Out[34]:
(1, 2, 3)
In [35]:
# Czytamy tak samo
a[0]
Out[35]:
1
In [36]:
b = (2,3,4)

c = a + b
c
Out[36]:
(1, 2, 3, 2, 3, 4)
In [38]:
d = b + c
d
Out[38]:
(2, 3, 4, 1, 2, 3, 2, 3, 4)
In [39]:
# Co się teraz stanie?
a[1]=1
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-39-50f053ed6a41> in <module>()
      1 # Co się teraz stanie?
----> 2 a[1]=1

TypeError: 'tuple' object does not support item assignment

Dictionaries

In [43]:
oceny = {'polski': 3.5, 
         'matematyka': 5,
         'fizyka': 4, 
         'informatyka': 6}
oceny
Out[43]:
{'fizyka': 4, 'informatyka': 6, 'matematyka': 5, 'polski': 3.5}
In [44]:
# Odczytanie wartości dla klucza
oceny['informatyka']
Out[44]:
6
In [45]:
# A teraz?
oceny['wf']
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-45-1ab3a7593b76> in <module>()
      1 # A teraz?
----> 2 oceny['wf']

KeyError: 'wf'
In [46]:
# Łatwo można dodać ocenę
oceny['nowy przedmiot'] = 2.0
oceny
Out[46]:
{'fizyka': 4,
 'informatyka': 6,
 'matematyka': 5,
 'nowy przedmiot': 2.0,
 'polski': 3.5}
In [47]:
# A także nadpisać 
oceny['nowy przedmiot'] = 4.0
oceny
Out[47]:
{'fizyka': 4,
 'informatyka': 6,
 'matematyka': 5,
 'nowy przedmiot': 4.0,
 'polski': 3.5}

Sets

In [48]:
# Zbiory. Takie jak w matematyce. Jakie są dwie podstawowe włąsności zbiorów? 
ulubione_przedmioty = set(['polski', 'muzyka', 'geografia', 'historia'])
ulubione_przedmioty
Out[48]:
{'geografia', 'historia', 'muzyka', 'polski'}
In [49]:
# Czy element należy do zbioru?
'informatyka' in ulubione_przedmioty
#'polski' in ulubione_przedmioty
Out[49]:
False
In [50]:
# Zastosowanie z ifem (data flow będzie dalej)
# UWAGA NA WCIĘCIA
if 'polski' in ulubione_przedmioty:
    print('Kocham j. polski!')
Kocham j. polski!
In [51]:
a = set(['a','b','c','d'])
b = set(['c','d','e','f'])
a = a.union(b)
l = list(a)
print(l)
['a', 'c', 'd', 'e', 'b', 'f']
In [52]:
a.intersection(b)
Out[52]:
{'c', 'd', 'e', 'f'}
In [53]:
a.difference(b)
Out[53]:
{'a', 'b'}
In [54]:
# Jak usunąć duplikaty z listy?
l = [1, 2, 'b', 4, 2, 'b', 'c']
s = set(l)
nl = list(s)
print(nl)
['c', 1, 2, 4, 'b']
In [55]:
# Dlaczego nie można tak?
s = set(['a', 'b', 'c'])
pos = s.index('a')
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-55-ebdf255d54e5> in <module>()
      1 # Dlaczego nie można tak?
      2 s = set(['a', 'b', 'c'])
----> 3 pos = s.index('a')

AttributeError: 'set' object has no attribute 'index'

Strings

In [56]:
a = 4
print('asdasdas  ' + str(a))
asdasdas  4
In [57]:
# łańcuchy znaków...
print('Imię: {}'.format('Wojciech'))
Imię: Wojciech
In [58]:
from math import pi
print(' Imię:     {},\n Nazwisko: {},\n PESEL:    {},\n Ulubiona: {}\n'
    .format('Wojciech', 'Jaśkowski', '8212...', pi))
 Imię:     Wojciech,
 Nazwisko: Jaśkowski,
 PESEL:    8212...,
 Ulubiona: 3.141592653589793

In [60]:
# Można nadać identyfikator {identyfikator}
# Czy kolejnośc ma w takim razie znaczenie?
from math import pi
print(''' 
Imię:     {imie},
Nazwisko: {nazw},
PESEL:    {pesel},
Ulubiona: {ulub}
'''.format(
    nazw='Jaśkowski', 
    imie='Wojciech', 
    pesel='8212...', 
    ulub=pi))
 
Imię:     Wojciech,
Nazwisko: Jaśkowski,
PESEL:    8212...,
Ulubiona: 3.141592653589793

In [61]:
# Czy da radę to wyświetlić?
print('ęśćńżół')
print('יהוה')
ęśćńżół
יהוה
In [62]:
# Po łańcuchu znaków można w sumie iterować, więc...
s = 'ala'
print(s[0:2])
al
In [63]:
# Czy jest jakaś różnica?
print('ala')
print("ala")
ala
ala
In [64]:
# Ciekawostka
print('ala ma \' "kota"')
print("ala ma 'kota'")
ala ma ' "kota"
ala ma 'kota'
In [65]:
# Bardzo łatwo można w pythonie dokonywać konwersji między łańcuchem znaków a inną zmienną.
str(12)
Out[65]:
'12'
In [66]:
int('12')
Out[66]:
12
In [67]:
float('12.1')
Out[67]:
12.1
In [69]:
text = 'Python is easy;really?'
text.split()
Out[69]:
['Python', 'is', 'easy;really?']
In [70]:
text.split(';')
Out[70]:
['Python is easy', 'really?']
In [71]:
# Wciąż nie fajnie, ale...
import re
re.split(' |;', text)
Out[71]:
['Python', 'is', 'easy', 'really?']
In [72]:
arr = ['a','b','c','d']
str(arr)
Out[72]:
"['a', 'b', 'c', 'd']"
In [73]:
'; '.join(arr)
Out[73]:
'a; b; c; d'

Flow control

In [74]:
arr = ['a', 'b', 'c', 'd']
for a in arr:
    print(a)
a
b
c
d
In [75]:
list(range(0, 4))
Out[75]:
[0, 1, 2, 3]
In [76]:
for i in range(len(arr)):
    print(i, arr[i])
0 a
1 b
2 c
3 d
In [81]:
# W poprzednich podejściach mieliśmy albo element, albo indeks. 
# A można mieć to i to 

#list(enumerate(arr))

for i, a in enumerate(arr):
    print(i, a)
0 a
1 b
2 c
3 d
In [82]:
a = [0,1,2,3]
b = ['a','b','c','d']
n = len(a)
for i in range(n):
    print(a[i], b[i])
0 a
1 b
2 c
3 d
In [83]:
# A co jeżeli chcemy iterować jednocześnie po dwóch listach?
a = [0,1,2,3]
b = ['a','b','c','d']
for x, y in zip(a, b):
    print(x, y)
0 a
1 b
2 c
3 d
In [84]:
list(zip(a,b))
Out[84]:
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]
In [85]:
# A po trzech?
c=['ala','ma','kota','!']
zipped = list(zip(a,b,c))
zipped
Out[85]:
[(0, 'a', 'ala'), (1, 'b', 'ma'), (2, 'c', 'kota'), (3, 'd', '!')]
In [86]:
# Skoro można 'zipować', to można także 'odzipować'
a, b, c = list(zip(*zipped))
print(a)
print(b)
print(c)
(0, 1, 2, 3)
('a', 'b', 'c', 'd')
('ala', 'ma', 'kota', '!')
In [87]:
# If w pythonie jest bardzo prosty (pamiętamy o ':' oraz braku '{ }')
arr = [0,1,2,3]
for a in arr:
    if (a % 3 == 0):
        print('0 = {} mod 3'.format(a))
    elif a % 3 == 1:
        print('1 = {} mod 3'.format(a))
    else:
        print('2 = {} mod 3'.format(a))
0 = 0 mod 3
1 = 1 mod 3
2 = 2 mod 3
0 = 3 mod 3
In [88]:
# Pętla while to też pestka. Jaki tu będzie wynik?
s = 'python'
while s[0] != 'h':
    s = s[1:]
print(s)
hon
In [89]:
# and (nawiasy nie są konieczne)
a = 1
if -1 <= a and (a <= 1):
    print('A is in range')
A is in range
In [90]:
# 'and' czasami też nie jest konieczny...
if -1 <= a <= 1:
    print('A is in range')
A is in range
In [91]:
# negacja 
a = [1, 2, 3]
if not 4 in a:
    print('4 is missing')
4 is missing
In [93]:
# continue, break
a = 2
while (a < 5):
    a = a + 1
    print(a)
    if (a == 3):
        break
        #continue
3

Iterating over dictionaries

In [98]:
# Co odczytujemy?
# Co z kolejnością?

d = {'a': 1, 
     'b': 2, 
     12: 'mama', 
     4:23}

for v in d:
    print(str(v) + ' => ' + str(d[v]))
12 => mama
a => 1
4 => 23
b => 2
In [101]:
# A gdybyśmy chcieli mieć klucz i wartość od razu?

#list(d.items())

for k, v in d.items():
    print(str(k) + ' => ' + str(v))
12 => mama
a => 1
4 => 23
b => 2

Functions

In [102]:
# Na początek proste dodawanie (pamiętamy o wcięciach, ':' oraz braku '{ }')

def suma(a, b): 
    return a + b
        
if suma(1,3) == 4: print("ok") # można w jednej linijce
ok
In [103]:
# Python wspiera wartości domyślne funkcji. Jaki będzie wynik?
def suma(a, 
         b, 
         wa=1, 
         wb=3):
    return wa * a + wb * b

suma(1,1)
Out[103]:
4
In [104]:
# A teraz?
suma(1, 3, 2, 1)
Out[104]:
5
In [106]:
# Zamieniliśmy kolejność, odwołując się po identyfikatorach. Czy teraz się wyjdzie?
suma(1, 3, wb=2, wa=1)
Out[106]:
7
In [107]:
print(suma(1, 3, wa=2))
11
In [108]:
# Co ta funkcja robi?
# Ile wartości ona zwraca?
def f(arr):
    n = x = arr[0]
    for a in arr:
        if n > a:
            n = a
        if x < a:
            x = a
    return n, x

print(f([2,3,1,4]))
(1, 4)
In [109]:
# Jak to przechwycić?
a = f([2,3,1,4])
print(a)
a, b = f([2,3,1,4])
print(a)
print(b)
(1, 4)
1
4
In [112]:
# Czym jest x?
x = f([2,3,1,4])
type(x)
Out[112]:
tuple
In [113]:
# Przkład operacji a, b = b, a (swap)
a = 1
b = 2
a, b = b, a
print('a = ' + str(a))
print('b = ' + str(b))
a = 2
b = 1
In [114]:
# Taki inny unzip
x = ('ala','ma','kota')
a, b, c = x
print('a = ' + str(a))
print('b = ' + str(b))
print('c = ' + str(c))
a = ala
b = ma
c = kota
In [115]:
# Pytanie za zero punktów. Co zwraca funkcja f?
def f(wa=1, wb=1):   
    def g(a, b):
        return a * wa + b * wb;
    return g

f(1,3)
Out[115]:
<function __main__.f.<locals>.g>
In [117]:
# W Javie czym musimy się posłużyć, żeby uzyskać taki efekt? 
wazona = f(0, 1)
wazona
Out[117]:
<function __main__.f.<locals>.g>
In [118]:
wazona(1, 3)
Out[118]:
3
In [119]:
# Gratisowa metoda listy. Wynik?
arr = [-3, 2, 1, 4]
arr.sort()
arr
Out[119]:
[-3, 1, 2, 4]
In [120]:
# A teraz?
arr.sort(reverse=True)
arr
Out[120]:
[4, 2, 1, -3]
In [121]:
# A teraz?
def mykey(x):
    return abs(x)
arr.sort(key=mykey)
arr
Out[121]:
[1, 2, -3, 4]
In [122]:
# Możemy to zrobić 'inline' wykorzystując funkcje lambda.
arr.sort(key=lambda x: abs(x))
arr
Out[122]:
[1, 2, -3, 4]
In [123]:
# Utrwalmy funkcje lambda. Jaki będzie wynik?
f = lambda a, b: a - b
print(f(1,2))
-1
In [124]:
# A teraz?
g = lambda a, b: a + b
print(g(1,2))
3
In [125]:
# A teraz? 
f, g = g, f
print(f(1,2))
print(g(1,2))
3
-1

Various

Complex numbers

In [126]:
# Python obsługuje liczby zespolone
1+3j
Out[126]:
(1+3j)
In [127]:
# Czym jest moduł liczby zepolonej?
abs(1+3j)
Out[127]:
3.1622776601683795
In [128]:
(1+3j)*(2-1j)
Out[128]:
(5+5j)

Generators (yield)

In [129]:
# Normalnie, po wykonaniu funkcji, jej stan lokalny jest niszczony. Ale...
# Co robi ten kod?

def whatdoido():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

print(whatdoido())
<generator object whatdoido at 0x1053dde08>
In [130]:
# Wynik?
g = whatdoido()
print(next(g))
0
In [131]:
# A teraz?
print(next(g))
print(next(g))
print(next(g))
1
1
2
In [132]:
# Można tak
for i in range(10):
    print(next(g))
3
5
8
13
21
34
55
89
144
233
In [79]:
# Co teraz chcemy otrzymać?
for v in whatdoido():
    if v > 100:
        break
    print(v)
0
1
1
2
3
5
8
13
21
34
55
89
In [134]:
# Ten kod tworzy wszytkie k-elementowe kombinacje z iterowalnego obiektu 
# (np. listy, ciągu znaków). Są tutaj dwie fajne rzeczy.
def combinations(iterable, k):
    # combinations('ABCD', 2) --> AB AC AD BC BD CD
    # combinations(range(4), 3) --> 012 013 023 123
    pool = tuple(iterable)
    print (pool)
    n = len(pool)
    if k > n:
        return
    indices = list(range(k))
    print(indices)
    yield tuple(pool[i] for i in indices)
    while True:
        for i in reversed(range(k)):
            if indices[i] != i + n - k:
                break
        # Pierwsza fajna rzecz
        else:
            return
        indices[i] += 1
        for j in range(i+1, k):
            indices[j] = indices[j-1] + 1
        yield tuple(pool[i] for i in indices)
        
pairs = combinations('ABCD', 2)
print(pairs)
# Druga fajna rzecz. Ale musimy uważać, przy tworzeniu generatora (return)
for pair in pairs:
    print(pair)
<generator object combinations at 0x1053853b8>
('A', 'B', 'C', 'D')
[0, 1]
('A', 'B')
('A', 'C')
('A', 'D')
('B', 'C')
('B', 'D')
('C', 'D')
In [135]:
# Pierwsze trzy pary, które mają A i G w środku
pairs = combinations('ABCDEFGH', 3)
found = 0
for pair in pairs:
    if 'A' in pair and 'G' in pair and found < 3:
        found += 1
        print(pair)
('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H')
[0, 1, 2]
('A', 'B', 'G')
('A', 'C', 'G')
('A', 'D', 'G')

Build-in functions

In [139]:
# Dwa przykłady poniżej są fajne, bo można np. wczytać sobie z jednego skrytpu drugi, 
# i go wykonać
x=1
eval('max([x,2,-2,3])')
Out[139]:
3
In [140]:
exec('import math; print(math.sin(2*math.pi))')
-2.4492935982947064e-16
In [141]:
# Funkcje logiczne
print(all([True, False, True]))
print(any([True, False, True]))
False
True
In [142]:
# Funkcje matematyczne
print(sum([1,2,3]))
print(min([1,2,3]))
print(max([1,2,3]))
6
1
3
In [143]:
# Inne funkcje matematyczne
print(abs(-12))
print(round(3.14159, 3))
12
3.142
In [144]:
# Pamiętamy? Konwersja w pythonie jest łatwa.
print(float(12))
print(int(12.7))
12.0
12
In [145]:
print(str(123))
print(str([1,2,3]))
123
[1, 2, 3]
In [146]:
# Znak -> numer w unicode i na odwrót. 
print(ord('a'))
print(chr(98))
97
b
In [147]:
# Fajna funkcja. Do debugowania
print(type('ala ma kota'))
print(type([1,2,3]))
<class 'str'>
<class 'list'>

Global

In [148]:
# Trochę o zmiennych globalnych. 
text = 'ala ma kota'

def a():
    print('a: ' + text) 
def b():
    print('b: '  + text)
    text = 'ala ma psa'    
In [149]:
# Wynik?
a()
a: ala ma kota
In [150]:
# Wynik?
b()
---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
<ipython-input-150-aa88c51cf9ea> in <module>()
      1 # Wynik?
----> 2 b()

<ipython-input-148-5411e91096b5> in b()
      5     print('a: ' + text)
      6 def b():
----> 7     print('b: '  + text)
      8     text = 'ala ma psa'

UnboundLocalError: local variable 'text' referenced before assignment
In [151]:
# Zmienne globalne są niebezpieczne. Python chce, żebyśmy mu dali znać,
# że wiemy co robimy :)
text = 'ala ma kota'
def c():
    global text
    print('c: '  + text)
    text = 'ala ma psa'

c()
print(text)
c: ala ma kota
ala ma psa

Comprehensions

Lists

In [153]:
# To są fajne rzeczy. Warto zapamiętać - super oszczędność kodu!
# Jakby wyglądało 'klasyczne' przeniesienie alementow jednej listy do drugiej + coś jeszcze

arr = [0,1,2,3,4,5]
new = []
for a in arr:
    new.append('A' + str(a))
new
Out[153]:
['A0', 'A1', 'A2', 'A3', 'A4', 'A5']
In [154]:
# W pythonie można tak:

arr = [0,1,2,3,4,5]
new = ['A' + str(a) for a in arr]
new
Out[154]:
['A0', 'A1', 'A2', 'A3', 'A4', 'A5']
In [155]:
# Można dodać warunek. Czyli ogólnie: [funkcja for if]
arr = [0,1,2,3,4,5]
new = ['A' + str(a) for a in arr if a % 2 == 0]
new
Out[155]:
['A0', 'A2', 'A4']
In [156]:
# Co to robi?
arr = [0,13,2,4,11]
sum([1 for a in arr if a % 2 == 0])
Out[156]:
3
In [157]:
# Chcemy wszystkie pierwsze litery wyrazów zamienić na wielkie
text = 'to jest krótki text nie na temat'
splitted = text.split()
splitted
Out[157]:
['to', 'jest', 'krótki', 'text', 'nie', 'na', 'temat']
In [158]:
big = [x[0].upper() + x[1:] for x in splitted]
big
Out[158]:
['To', 'Jest', 'Krótki', 'Text', 'Nie', 'Na', 'Temat']
In [159]:
# Trochę długaśne. Swoją drogą - fajne wykorzystanie str.join.
" ".join(big)
Out[159]:
'To Jest Krótki Text Nie Na Temat'
In [160]:
# Można to zrobić krócej:
text = 'to jest krótki text nie na temat'
print(" ".join([x[0].upper() + x[1:] for x in text.split()]))
To Jest Krótki Text Nie Na Temat
In [161]:
# Co, gdybyśmy chcieli coś zrobić, z każdą komórka 2d macierzy?

m = [[0,1,1,0],
     [1,0,1,0],
     [0,1,0,1],
     [1,0,0,1]]
nm = [[1 - cell for cell in row] for row in m]
print(m)
print(nm)
[[0, 1, 1, 0], [1, 0, 1, 0], [0, 1, 0, 1], [1, 0, 0, 1]]
[[1, 0, 0, 1], [0, 1, 0, 1], [1, 0, 1, 0], [0, 1, 1, 0]]
In [162]:
# Tutaj pamietamy o klamrach 
# Co to robi?
przedmioty = ('matematyka', 'fizyka', 'chemia')
slownik = {p: len(p) for p in przedmioty}
slownik
Out[162]:
{'chemia': 6, 'fizyka': 6, 'matematyka': 10}

Classes

In [168]:
# Krótko omówimy klasy (tak, python jest obiektowy)
# __init__, self

class Circle:
    
    def __init__(self, radius):
        self.radius = radius 
        self.costam = 2
   
    def area(self):
        from math import pi
        self.size = pi * self.radius**2
        return self.size
    
    def set_radius(self, radius):
        self.radius = radius    
        
c = Circle(3)
print(c.area())
c.set_radius(5)     
28.274333882308138
In [169]:
print(c.radius)
5
In [170]:
# W pythonie nie ma '{ }' więc jak zrobić pustą klasę?
# Pamiętamy, że w pythonie nie trzeba deklarować.
# Wynik?

class Container:
    pass

def compute(container):
    return container.size**2

c = Container
c.size = 2;

compute(c)
Out[170]:
4
In [171]:
# Atrybuty 'statyczne' i dla instancji.
class Przedmiot:
    acoto = 12
    alefajnie = 2
    def __init__(self, nazwa):
        self.nazwa = nazwa
      
        
p = Przedmiot('kck')
p.nazwa
Out[171]:
'kck'
In [172]:
print(p.acoto)
print(Przedmiot.alefajnie)
print(Przedmiot.acoto)
Przedmiot.acoto = 5
print(Przedmiot.acoto)
12
2
12
5
In [173]:
# Wygląda brzydko. A jak robiliśmy print(lista) to było ładnie. 
print(p)
<__main__.Przedmiot object at 0x105401cf8>
In [174]:
# Można temu zaradzić
class Przedmiot:    
    def __init__(self, nazwa):
        self.nazwa = nazwa
        
    def __repr__(self):
        return 'Przedmiot o nazwie ' + self.nazwa
    
p = Przedmiot('KCK')
print(p)
Przedmiot o nazwie KCK

Duck typing

In [175]:
class Circle:
    def __init__(self, radius):
        self.radius = radius            
    def area(self):
        from math import pi
        return pi * self.radius**2

class Square:
    def __init__(self, w):
        self.w = w
    def area(self):
        return self.w**2
    
class Line:
    pass
    
def get_shape():
    from random import choice
    return choice([Square(4), Circle(4), Line()])
    
shape = get_shape()
shape.area()
Out[175]:
50.26548245743669

Files

In [176]:
# Pisanie do pliku jest proste
f = open('test.txt','w')
for i in range(6):
    f.write('To jest linia {}\n'.format(i))
f.close()
In [177]:
cat test.txt
To jest linia 0
To jest linia 1
To jest linia 2
To jest linia 3
To jest linia 4
To jest linia 5
In [178]:
# Czytanie też. Jak iterujemy plik, to czytamy linie.
f = open('test.txt')
for line in f:
    print(line.strip())
f.close()
To jest linia 0
To jest linia 1
To jest linia 2
To jest linia 3
To jest linia 4
To jest linia 5
In [179]:
# Można tak
with open('test.txt') as f:
    for line in f:
        print(line.strip())
To jest linia 0
To jest linia 1
To jest linia 2
To jest linia 3
To jest linia 4
To jest linia 5
In [180]:
# Można od razu wczytac wsystkie linie i dalej używać.
with open('test.txt') as f:
    lines = f.readlines()
lines[1]
Out[180]:
'To jest linia 1\n'
In [ ]:
http://www.learnpython.org/en/Welcome  
In [ ]:
https://www.hackerrank.com/domains/python/py-introduction
In [184]:
%matplotlib inline
import matplotlib.pyplot as plt

plt.figure(figsize=(5, 5))
plt.plot([100,200,300,400],[0.1,0.2,0.8,0.9])
#plt.savefig('myplot.pdf')
#plt.close()
Out[184]:
[<matplotlib.lines.Line2D at 0x106f907b8>]
In [ ]: