Numbers

In [1]:
2**31
Out[1]:
2147483648
In [2]:
2**63
Out[2]:
9223372036854775808
In [3]:
2**64
Out[3]:
18446744073709551616
In [4]:
2**128
Out[4]:
340282366920938463463374607431768211456
In [5]:
2**4000
Out[5]:
13182040934309431001038897942365913631840191610932727690928034502417569281128344551079752123172122033140940756480716823038446817694240581281731062452512184038544674444386888956328970642771993930036586552924249514488832183389415832375620009284922608946111038578754077913265440918583125586050431647284603636490823850007826811672468900210689104488089485347192152708820119765006125944858397761874669301278745233504796586994514054435217053803732703240283400815926169348364799472716094576894007243168662568886603065832486830606125017643356469732407252874567217733694824236675323341755681839221954693820456072020253884371226826844858636194212875139566587445390068014747975813971748114770439248826688667129237954128555841874460665729630492658600179338272579110020881228767361200603478973120168893997574353727653998969223092798255701666067972698906236921628764772837915526086464389161570534616956703744840502975279094087587298968423516531626090898389351449020056851221079048966718878943309232071978575639877208621237040940126912767610658141079378758043403611425454744180577150855204937163460902512732551260539639221457005977247266676344018155647509515396711351487546062479444592779055555421362722504575706910949376
In [6]:
len(str(2**4000))
Out[6]:
1205

Data types

Lists

In [7]:
arr = [0,1,2,3]
print(arr)
[0, 1, 2, 3]
In [8]:
arr = [1,2,'cos', [10,11,12], 3.14]
arr
Out[8]:
[1, 2, 'cos', [10, 11, 12], 3.14]
In [9]:
arr = [0,1,2,3]
arr
Out[9]:
[0, 1, 2, 3]
In [10]:
len(arr)
Out[10]:
4
In [11]:
arr[1]
Out[11]:
1
In [12]:
arr[-1]
Out[12]:
3
In [13]:
arr[1:3]
Out[13]:
[1, 2]
In [14]:
arr[:3]
Out[14]:
[0, 1, 2]
In [15]:
arr[-2:]
Out[15]:
[2, 3]
In [16]:
arr[-3:-1]
Out[16]:
[1, 2]
In [17]:
arr = [0,1,2,3,4,5,6]
arr[0:5]
Out[17]:
[0, 1, 2, 3, 4]
In [18]:
arr[0:5:2]
Out[18]:
[0, 2, 4]
In [19]:
arr[::2]
Out[19]:
[0, 2, 4, 6]
In [20]:
arr[::-1]
Out[20]:
[6, 5, 4, 3, 2, 1, 0]
In [21]:
a=[0,1,2,3]
b=['a','b','c','d']
a+b
Out[21]:
[0, 1, 2, 3, 'a', 'b', 'c', 'd']
In [22]:
a=[10,20,30,40]
a.append(100)
a
Out[22]:
[10, 20, 30, 40, 100]
In [23]:
a=[10,20,20,30,40]
a.remove(20)
a
Out[23]:
[10, 20, 30, 40]

Tuples

In [24]:
a = (1,2,3)
a
Out[24]:
(1, 2, 3)
In [25]:
a[0]
Out[25]:
1
In [26]:
try:
    a[1]=1
except Exception as e:
    print('Exception:', e)
Exception: 'tuple' object does not support item assignment

Dictionaries

In [27]:
oceny = {'polski': 3.5, 'matematyka': 5, 'fizyka': 4, 
         'informatyka': 6}
oceny
Out[27]:
{'fizyka': 4, 'informatyka': 6, 'matematyka': 5, 'polski': 3.5}
In [28]:
oceny['informatyka']
Out[28]:
6
In [29]:
oceny['nowy przedmiot'] = 2.0
oceny
Out[29]:
{'fizyka': 4,
 'informatyka': 6,
 'matematyka': 5,
 'nowy przedmiot': 2.0,
 'polski': 3.5}

Sets

In [30]:
ulubione_przedmioty = set(['polski', 'muzyka', 'geografia', 'historia'])
ulubione_przedmioty
Out[30]:
{'geografia', 'historia', 'muzyka', 'polski'}
In [31]:
'informatyka' in ulubione_przedmioty
Out[31]:
False
In [32]:
if 'polski' in ulubione_przedmioty:
    print('Kocham j. polski!')
Kocham j. polski!
In [33]:
a = set(['a','b','c','d'])
b = set(['c','d','e','f'])
a.union(b)
Out[33]:
{'a', 'b', 'c', 'd', 'e', 'f'}
In [34]:
a.intersection(b)
Out[34]:
{'c', 'd'}
In [35]:
a.difference(b)
Out[35]:
{'a', 'b'}

Strings

In [36]:
print('Imię: {}'.format('Wojciech'))
Imię: Wojciech
In [37]:
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 [38]:
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 [39]:
print('ęśćńżół')
print('יהוה')
ęśćńżół
יהוה
In [40]:
s = 'ala'
print(s[0:2])
al
In [41]:
print('ala')
print("ala")
ala
ala
In [42]:
print('ala ma "kota"')
print("ala ma 'kota'")
ala ma "kota"
ala ma 'kota'
In [43]:
str(12)
Out[43]:
'12'
In [44]:
int('12')
Out[44]:
12
In [45]:
float('12.1')
Out[45]:
12.1
In [46]:
text = 'Python is easy;really?'
text.split()
Out[46]:
['Python', 'is', 'easy;really?']
In [47]:
text.split(';')
Out[47]:
['Python is easy', 'really?']
In [48]:
import re
re.split(' |;', text)
Out[48]:
['Python', 'is', 'easy', 'really?']
In [49]:
arr = ['a','b','c','d']
str(arr)
Out[49]:
"['a', 'b', 'c', 'd']"
In [50]:
'; '.join(arr)
Out[50]:
'a; b; c; d'

Flow control

In [51]:
arr = ['a', 'b', 'c', 'd']
for a in arr:
    print(a)
a
b
c
d
In [52]:
list(range(4))
Out[52]:
[0, 1, 2, 3]
In [53]:
for i in range(len(arr)):
    print(i, arr[i])
0 a
1 b
2 c
3 d
In [54]:
for i, a in enumerate(arr):
    print(i, a)
0 a
1 b
2 c
3 d
In [55]:
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 [56]:
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 [57]:
list(zip(a,b))
Out[57]:
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]
In [58]:
c=['ala','ma','kota','!']
zipped = list(zip(a,b,c))
zipped
Out[58]:
[(0, 'a', 'ala'), (1, 'b', 'ma'), (2, 'c', 'kota'), (3, 'd', '!')]
In [59]:
a, b, c = list(zip(*zipped))
print(a)
print(b)
print(c)
(0, 1, 2, 3)
('a', 'b', 'c', 'd')
('ala', 'ma', 'kota', '!')
In [60]:
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)
3 = 0 (mod 3)
In [61]:
12 // 5
Out[61]:
2
In [62]:
s = 'python'
while s[0] != 'h':
    s = s[1:]
print(s)
hon
In [63]:
a = 1
if -1 <= a and a <= 1:
    print('A is in range')
A is in range
In [64]:
if -1 <= a <= 1:
    print('A is in range')
A is in range
In [65]:
a = [1, 2, 3]
if not 4 in a:
    print('4 is missing')
    
4 is missing
In [66]:
# or, continue, break

Iterating over dictionaries

In [67]:
d = {'a': 1, 'b': 2, 12: 'mama'}
for v in d:
    print(v)
a
12
b
In [68]:
for k, v in d.items():
    print(str(k) + ' => ' + str(v))
a => 1
12 => mama
b => 2

Functions

In [69]:
def suma(a, b):    
    return a + b
        
suma(1,3)
Out[69]:
4
In [70]:
def suma(a, b, wa=1, wb=1):
    return wa * a + wb * b

print(suma(1, 3))
4
In [71]:
print(suma(1, 3, 2, 1))
5
In [72]:
print(suma(1, 3, wb=2, wa=1))
7
In [73]:
print(suma(1, 3, wb=2))
7
In [74]:
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 [75]:
a, b = f([2,3,1,4])
print(a)
print(b)
1
4
In [76]:
x = f([2,3,1,4])
x
Out[76]:
(1, 4)
In [77]:
a = 1
b = 2
a, b = b, a
print('a = ' + str(a))
print('b = ' + str(b))
a = 2
b = 1
In [78]:
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 [79]:
def f(wa=1, wb=1):   
    def g(a, b):
        return a * wa + b * wb
    return g

f(1,3)
Out[79]:
<function __main__.f.<locals>.g>
In [80]:
wazona = f(0, 1)
wazona(1,2)
Out[80]:
2
In [81]:
wazona(1, 3)
Out[81]:
3
In [82]:
arr = [-3, 2, 1, 4]
arr.sort()
arr
Out[82]:
[-3, 1, 2, 4]
In [83]:
arr.sort(reverse=True)
arr
Out[83]:
[4, 2, 1, -3]
In [84]:
def mykey(x):
    return abs(x)
arr.sort(key=mykey)
arr
Out[84]:
[1, 2, -3, 4]
In [85]:
arr.sort(key=lambda x: abs(x))
arr
Out[85]:
[1, 2, -3, 4]
In [86]:
f = lambda a, b: a - b
print(f(1,2))
-1
In [87]:
g = lambda a, b: a + b
print(g(1,2))
3
In [88]:
f, g = g, f
print(f(1,2))
print(g(1,2))
3
-1

Various

Complex numbers

In [89]:
1+3j
Out[89]:
(1+3j)
In [90]:
abs(1+3j)
Out[90]:
3.1622776601683795
In [91]:
(1+3j)*(2-1j)
Out[91]:
(5+5j)

Generators (yield)

In [92]:
def whatdoido():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b
        
print(whatdoido())
<generator object whatdoido at 0x109891b48>
In [93]:
g = whatdoido()
print(next(g))
0
In [94]:
print(next(g))
print(next(g))
print(next(g))
1
1
2
In [95]:
for i in range(10):
    print(next(g))
3
5
8
13
21
34
55
89
144
233
In [96]:
for v in whatdoido():
    if v > 100:
        break
    print(v)
0
1
1
2
3
5
8
13
21
34
55
89
In [97]:
def combinations(iterable, r):
    # combinations('ABCD', 2) --> AB AC AD BC BD CD
    # combinations(range(4), 3) --> 012 013 023 123
    pool = tuple(iterable)
    n = len(pool)
    if r > n:
        return
    indices = list(range(r))
    yield tuple(pool[i] for i in indices)
    while True:
        for i in reversed(range(r)):
            if indices[i] != i + n - r:
                break
        else:
            return
        indices[i] += 1
        for j in range(i+1, r):
            indices[j] = indices[j-1] + 1
        yield tuple(pool[i] for i in indices)
        
pairs = combinations('ABCD', 2)
print(pairs)
for pair in pairs:
    print(pair)
<generator object combinations at 0x109dd2830>
('A', 'B')
('A', 'C')
('A', 'D')
('B', 'C')
('B', 'D')
('C', 'D')
In [98]:
# 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', 'G')
('A', 'C', 'G')
('A', 'D', 'G')

Build-in functions

In [99]:
x=1
eval('max([x,2,-2,3])')
Out[99]:
3
In [100]:
exec('import math; print(math.sin(2*math.pi))')
-2.4492935982947064e-16
In [101]:
print(all([True, False, True]))
print(any([True, False, True]))
False
True
In [102]:
print(sum([1,2,3]))
print(min([1,2,3]))
print(max([1,2,3]))
6
1
3
In [103]:
print(abs(-12))
print(round(3.14159, 3))
12
3.142
In [104]:
print(float(12))
print(int(12.7))
12.0
12
In [105]:
print(str(123))
print(str([1,2,3]))
123
[1, 2, 3]
In [106]:
print(ord('a'))
print(chr(98))
97
b
In [107]:
print(type('ala ma kota'))
print(type([1,2,3]))
<class 'str'>
<class 'list'>

Global

In [108]:
text = 'ala ma kota'

def a():
    print('a: ' + text) 
def b():
    print('b: '  + text)
    text = 'ala ma psa'    
In [109]:
a()
a: ala ma kota
In [110]:
try:
    b()
except:
    import traceback
    print(traceback.format_exc())
Traceback (most recent call last):
  File "<ipython-input-110-7a0d6c076f92>", line 2, in <module>
    b()
  File "<ipython-input-108-40e53298a877>", line 6, in b
    print('b: '  + text)
UnboundLocalError: local variable 'text' referenced before assignment

In [111]:
text = 'ala ma kota'
def c():
    global text
    print('c: '  + text)
    text = 'ala ma psa'
c()
c: ala ma kota

Comprehensions

Lists

In [112]:
arr = [0,1,2,3,4,5]
new = []
for a in arr:
    new.append('A' + str(a))
new
Out[112]:
['A0', 'A1', 'A2', 'A3', 'A4', 'A5']
In [113]:
arr = [0,1,2,3,4,5]
new = ['A' + str(a) for a in arr]
new
Out[113]:
['A0', 'A1', 'A2', 'A3', 'A4', 'A5']
In [114]:
arr = [0,1,2,3,4,5]
new = ['A' + str(a) for a in arr if a % 2 == 0]
new
Out[114]:
['A0', 'A2', 'A4']
In [115]:
arr = [0,13,2,4,11]
sum([1 for a in arr if a % 2 == 0])
Out[115]:
3
In [116]:
# Chcemy wszystkie pierwsze litery wyrazów zamienić na wielkie
text = 'to jest krótki text nie na temat'
splitted = text.split()
splitted
Out[116]:
['to', 'jest', 'krótki', 'text', 'nie', 'na', 'temat']
In [117]:
big = [x[0].upper() + x[1:] for x in splitted]
big
Out[117]:
['To', 'Jest', 'Krótki', 'Text', 'Nie', 'Na', 'Temat']
In [118]:
" ".join(big)
Out[118]:
'To Jest Krótki Text Nie Na Temat'
In [119]:
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

Dictionaries

In [120]:
przedmioty = ('matematyka', 'fizyka', 'chemia')
slownik = {p: len(p) for p in przedmioty}
slownik
Out[120]:
{'chemia': 6, 'fizyka': 6, 'matematyka': 10}

Classes

In [121]:
class Circle:
    def __init__(self, radius):
        self.radius = radius    
        
    def area(self):
        from math import pi
        return pi * self.radius**2
    
    def set_radius(self, radius):
        self.radius = radius    
        
c = Circle(3)
print(c.area())
c.set_radius(5)     
28.274333882308138
In [122]:
print(c.radius)
5
In [123]:
class Container:
    pass

c = Container()
c.size = 12
c.value = 10000

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

compute(c)
Out[123]:
144
In [124]:
class Przedmiot:
    acoto = 12
    def __init__(self, nazwa):
        self.nazwa = nazwa
        
p = Przedmiot('kck')
p.nazwa
Out[124]:
'kck'
In [125]:
print(p.acoto)
print(Przedmiot.acoto)
12
12
In [126]:
print(p)
<__main__.Przedmiot object at 0x109df5320>
In [127]:
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 [128]:
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
    
def get_shape():
    from random import choice
    return choice([Square(4), Circle(4)])
    
shape = get_shape()
shape.area()
Out[128]:
16

Files

In [129]:
f = open('test.txt','w')
for i in range(6):
    f.write('To jest linia {}\n'.format(i))
f.close()
In [130]:
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 [131]:
f = open('test.txt')
for line in f:
    print(line, end='')
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 [132]:
with open('test.txt') as f:
    for line in f:
        print(line, end='')
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 [133]:
with open('test.txt') as f:
    lines = f.readlines()
lines[1]
Out[133]:
'To jest linia 1\n'