Basic Python

Variables

In [24]:
a = 1
b = "some string"
c = 'string as well '
b_c = 'some string'

Python is a dynamically typed language

In [25]:
a = 1
print(a)
print(type(a)) # use type() to see object type
a = "asd"
print(a)
print(type(a))
a = [1,2,3]
print(a)
print(type(a))
1
<class 'int'>
asd
<class 'str'>
[1, 2, 3]
<class 'list'>

if

if simmilar to C/C++:

if condition :
    code
elif condition : (optional)
    code
else: (optional)
    code 
***or***
if(condition):
    code
elif(condition): (optional)
    code
else: (optional)
    code 

one line if:

code if condition else code

comparsion operators:

== - equal
!= - unequal
<, >, >=, <= - so on

In [1]:
b = "string"
b_c = "string"

if(b == b_c):
    print("a equals b")
else:
    print("nope")


if b != "bit infra":
    print("super")
a equals b
super

logical operators:

and - conjunction (&& w C++)
or - disjunction (|| w C++)
*not - negation (! w C++)

In [2]:
a = 1
b = '1'

if a == 1 and b == '1':
    print("OK")
else:
    print("Nope")
OK

Loops

while

while condition:
    code
In [2]:
i = 1
while(True):
    print(i)
    i+=1
1
2
3
4

for

for loop that iterates through something e. g.:

In [3]:
for i in range(1,5):
    print(i)
1
2
3
4

in general:

 for variable in iterable_object:
    code

In [5]:
a = [(1,2,3), (3,4,5)]

for x,y,_ in a:
    print(x, y)
1 2
3 4

Collections

list - array
tuple - tuple
dict - dictionary (HashMap(java), unordered_map(C++))
set - set (HashSet(java), unordered_set(C++))

In [31]:
a = [4,5,6] # list(4,5,6)
a.append(1)
a.append(2)
a.insert(1,3)
print(a)

a[0] = 24
print(a)

print(len(a))
print(a.pop())
print(a)
print(a[0])

print(5 in a)
[4, 3, 5, 6, 1, 2]
[24, 3, 5, 6, 1, 2]
6
2
[24, 3, 5, 6, 1]
24
True
In [9]:
a = (1,2)
print(type(a))
#a[1] = 3 # typles are immutable throws TypeError
print(a[0])
print(5 in a)

a = list(a) #converte to list
print(a)
a[1] = 3
print(a)
<class 'tuple'>
1
False
[1, 2]
[1, 3]
In [10]:
a = set()
a.add('a')
a.add('b')
print(a)
a.add('a')
a.remove('a')
print(a)
# a.remove('a') # throws an KeyError
if('a' in a):
    a.remove('a')
else:
    print("there is no a")
print(len(a))
{'b', 'a'}
{'b'}
there is no a
1
In [11]:
a = dict()
a[(1,2)] = "para 1"
a[(4,5)] = "para 2"

keys = list(a.keys())

print(keys)
print(a.items())
print((1,2) in a)
print((1,3) in a)
print(a[(1,2)])
del a[(1,2)]
#print(a[(1,2)]) # throws an KeyError
print(keys)
[(1, 2), (4, 5)]
dict_items([((1, 2), 'para 1'), ((4, 5), 'para 2')])
True
False
para 1
[(1, 2), (4, 5)]

N-dimensional arrays

We use generators:
[ variable for iterator/'_' in iterable_object ]
e g.:

In [28]:
b = input()
a = [int(i) for i in b.split()]
print(a)
a = [[1,2]]*10
a[0][1] = 3
a
123
[123]
Out[28]:
[[1, 3],
 [1, 3],
 [1, 3],
 [1, 3],
 [1, 3],
 [1, 3],
 [1, 3],
 [1, 3],
 [1, 3],
 [1, 3]]

Functions

def function_name(parameters divided by comma):
    code
In [29]:
def func(a,b,c):
    print(a)
    return b+c
In [30]:
r = func(1,2,3)
r
1
Out[30]:
5
In [31]:
def func2(a):
    print(a*2 + 1)
In [32]:
r = func2(2)
print(r)
5
None
In [34]:
def funcZ(a):
    
    def funcW(b):
        return b*a
    
    return funcW
In [35]:
my_f = funcZ(4)
print(my_f.__name__)
my_f(5)
funcW
Out[35]:
20
In [36]:
funcW(3)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-36-529d2743ae28> in <module>()
----> 1 funcW(3)

NameError: name 'funcW' is not defined

Importing libraries

import library_name

In [37]:
import numpy
a = numpy.array([1,2])
a
Out[37]:
array([1, 2])

import library_name as alias

In [38]:
import numpy as np
a = np.array([1,2])
a
Out[38]:
array([1, 2])

from library_name import function1, function2

In [39]:
from numpy import array, linspace
a = array([1,2])
print(linspace(1,5))
a
[1.         1.08163265 1.16326531 1.24489796 1.32653061 1.40816327
 1.48979592 1.57142857 1.65306122 1.73469388 1.81632653 1.89795918
 1.97959184 2.06122449 2.14285714 2.2244898  2.30612245 2.3877551
 2.46938776 2.55102041 2.63265306 2.71428571 2.79591837 2.87755102
 2.95918367 3.04081633 3.12244898 3.20408163 3.28571429 3.36734694
 3.44897959 3.53061224 3.6122449  3.69387755 3.7755102  3.85714286
 3.93877551 4.02040816 4.10204082 4.18367347 4.26530612 4.34693878
 4.42857143 4.51020408 4.59183673 4.67346939 4.75510204 4.83673469
 4.91836735 5.        ]
Out[39]:
array([1, 2])

from library_name import function1 as alias, function2 as alias

In [40]:
from numpy import array as ar, linspace as ls
a = ar([1,2])
print(ls(1,5))
a
[1.         1.08163265 1.16326531 1.24489796 1.32653061 1.40816327
 1.48979592 1.57142857 1.65306122 1.73469388 1.81632653 1.89795918
 1.97959184 2.06122449 2.14285714 2.2244898  2.30612245 2.3877551
 2.46938776 2.55102041 2.63265306 2.71428571 2.79591837 2.87755102
 2.95918367 3.04081633 3.12244898 3.20408163 3.28571429 3.36734694
 3.44897959 3.53061224 3.6122449  3.69387755 3.7755102  3.85714286
 3.93877551 4.02040816 4.10204082 4.18367347 4.26530612 4.34693878
 4.42857143 4.51020408 4.59183673 4.67346939 4.75510204 4.83673469
 4.91836735 5.        ]
Out[40]:
array([1, 2])

warning : can cause a mental diseases

from library_name import *

no examples for this s**t

In [47]:
a = [1, 2, 3]
b = a.copy()
b[1] = 50
a
Out[47]:
[1, 2, 3]

Classes

In [59]:
class ClassName(object):
    
    def __init__(cokolwiek, a, b, c):
        cokolwiek.a = a
        cokolwiek.b = b
        cokolwiek.__c = c
    
    def class_method(self):
        return self.a+self.b
    
    def method2(self, a, b):
        self.a += a
        self.b += b
        return self.a + self.b
    
    def __add__(self, ob2):
        return self.a + ob2.a
    
In [60]:
class_object1 = ClassName(2,3, 4)
print(class_object1.__c)
class_object2 = class_object1
class_object3 = ClassName(2,3)

class_object1.class_method()
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-60-7218ce05626f> in <module>()
      1 class_object1 = ClassName(2,3, 4)
----> 2 print(class_object1.__c)
      3 class_object2 = class_object1
      4 class_object3 = ClassName(2,3)
      5 

AttributeError: 'ClassName' object has no attribute '__c'
In [50]:
class_object1 + class_object3
Out[50]:
4
In [49]:
class_object1.method2(1, 1)
Out[49]:
7
In [50]:
print(class_object1.a, class_object1.b)
3 4
In [51]:
print(class_object2.a, class_object2.b)
3 4
In [52]:
print(class_object3.a, class_object3.b)
2 3

Print

In [3]:
print(1)
print("String")
print(1, "String", sep=':')
try: 
    print(1 + "String")
except:
    print("nope")
1
String
1:String
nope

much better

In [54]:
num = 1
string = "String"
print(f"{num} {string}")
1 String

with .format

*len(list of arguments) = n

In [70]:
num = 1
string = "String"
print("{1} {0} {0}".format(num, string), sep=' ')
print("{1} {0} {0}".format(num, string))

print('%s is %f' % (string, num))
String 1 1
String 1 1
String is 1.000000

*args

In [56]:
a = 3
b = 4
a, b = b, a
In [57]:
a
Out[57]:
4
In [58]:
b
Out[58]:
3
In [71]:
a, *args, b = 1, 2, 3, 4, 5, 6
In [75]:
a
Out[75]:
1
In [73]:
args
Out[73]:
[2, 3, 4, 5]
In [76]:
b
Out[76]:
6
In [78]:
def fun_arg(*arg):
    print("Item | index")
    for index, item in enumerate(arg):
        print(f"{item} | {index}")
In [79]:
fun_arg(5, 10 , 69)
Item | index
5 | 0
10 | 1
69 | 2

**kwargs

In [80]:
def fun(**kwargs):
    for key, value in kwargs.items():
        print(f"{key} = {value}")

fun(BIT="AI", JAVA="SCRIPT")
BIT = AI
JAVA = SCRIPT

Lambda

lambda variable : function

In [83]:
fun = (lambda x : x**2)

tab = [1,2,3]

[fun(x) for x in tab]
Out[83]:
[1, 4, 9]
In [84]:
for i in map(fun, tab):
    print(i)
1
4
9
In [86]:
tab = [5,4,-612,7,5,8]

tab.sort(key=(lambda x : (x%10)))
tab
Out[86]:
[4, 5, 5, 7, -612, 8]
In [97]:
s = "dima"
t = "filip"

sl = slice(0,3)
s[sl]
Out[97]:
'dim'
In [100]:
a = [[12,3,5,5,234], [1,234,4]]
Out[100]:
[[1, 234, 4]]