Python3 basics cheatsheet
Basic calculations
Exponentiation
2 ** 4 #out 16
Modulo: (Rest of the division)
5 % 2 #out 1
Variable definition
var=5
super_crazy_var=5
Comment:
# Some comment
String
String definition (In quotes):
"I can't touch anything"
Print variable:
print(var)
Format method:
print('My number is {} and my name is {}'.format(2,"Jan"))
Format method 2:
print('My number is {num} and my name is {name} and {num}'.format(num=2,name="Jan"))
Indexing of strings:
pintf(s[0])
Slicing: (From 0 to 4)
s="Hello world!"
s[:4] #out 'Hell'
Data types
Booleans:
True, False
List:
list = ['a', 'b', 'c']
List append:
list.append('d')
Change value in list:
list[0]="new value"
Neasted list:
list = [1,2,[1,2,["double_nested"]]]
print(list[3][2]) #output ["double_neasted"]
print(list[3][2][0]) #output "double_neasted"
Dictionary:
dic = {"key1":"value", "key2":1}
Neasted Dictionary:
dic = {"k1":{"inner_key":[1,2]}}
Touple(Immutable):
touple = (1,2,3)
print(t[0]) #out 1
Difference between tuple and list:
- List - Mutable
- Touple - Immutable
Set(collection of unique elements):
set={1,1,1,2,2,2,3} #out {1,2,3}
Array to Set conversion:
set([1,1,1,2,2,2,2,3,3]) #out {1,2,3}
Add to set:
set={1,1,1,2,2,2,3} #out {1,2,3}
set.add(5)
print(set) #out {1,2,3,5}
Comparators
Equal:
1 == 2 #False
And:
(1 < 2 )and (2 > 3) #False
Or:
(1 < 2) or (2 > 1) #True
If
if 1 < 2:
print('True')
If,elsif,else:
if 1 == 2:
print('Never')
elif 3 == 3:
print('True')
else:
print('else')
Loops
For:
seq = [1,2,3,4,5]
for num in seq:
print('Num: ' + str(num))
While:
i = 1
while i < 5:
print('i is: {}'.format(i))
i+=1
Range:
range(0, 5)
for x in range(0, 5):
print(x) # 0-5
List, range:
list(range(10))
List comprehension:
[num**2 for num in range(5)] #out [0, 1, 4, 9, 16]
Functions
Function:
def my_func(param1):
print(param1)
my_func('Hello world!')
my_func #out <function my_func at 0x7f81432c9b90> #what is the object
Default function parameter value:
def my_func(name='Default'):
print('Hello ' + name)
my_func() #out Hello Default
Function return:
def square(num):
return num**2
Documentation string:
def square(num):
"""
This is documentation
Multiple lines
"""
return num**2
Collection methods
Map function: Apply function to each element of seq
def times2(var):
return var*2
list(map(times2, list(range(4)))) #out [0, 2, 4, 6]
Lambda expressions:
times2 = lambda var:var*2
list(map(times2, list(range(4)))) #out [0, 2, 4, 6]
Pass lambda as param:
list(map(lambda num: num*3, list(range(4)))) #out [0, 3, 6, 9]
Filter:
list(filter(lambda num: num%2 == 0, range(4))) #out [0, 2]
String methods:
s = 'Some string value'
s.lower() # lowercase
s.upper() # uppercase
s.split() # split by whitespace
s.split('#pattern') # split by #pattern
Dictionary methods:
d = {'k1': 1, 'k2': 2}
d.keys() #out dict_keys(['k1', 'k2'])
d.items() #out dict_items([('k1', 1), ('k2', 2)])
d.values() #out dict_values([1, 2])
List methods:
list = [0,1,2,3,4]
list.pop() #return and remove last element, out 4
list.pop(0) #return and remove element of index 0, out 0
list.append("value") #out [1, 2, 3, 'value']
In operator:
'x' in [1, 2, 3] #out False
'x' in ['x', 'y', 'z'] #out True
Touple unpacking:
x = [(1,2),(3,4),(5,6)]
for (a,b) in x:
print(b) #out 2, 4, 6
Maybe you want to share? :)