Python Cheatsheet

Basic Data Types

Numbers

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#+-*/
x = (2+3*4)/7
print(x) #2.0
print(type(x)) #<class 'float'>
x += 1
print(x) #3.0
x *= 2
print(x) #6.0

#remainder
print(16 % 3) #1

#division returns floating point number
print(3/2) #1.5

#floor division
y = 3//2
print(y) #1
print(type(y)) #<class 'int'>

#square of 3
print(3**2) #9

#cube of 3
print(3**3) #27

#Python does not have increment ++ or decrement --

Booleans

1
2
3
4
5
6
7
t = True
f = False
print(type(t)) #<class 'bool'>
print(t and f) #False
print(t or f) #True
print(not t) #False
print(t != f) #True

Strings

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
print('in single quotes')
print("in double quotes isn't")

#don't regard \n as special characters
print(r'C:\some\name')

#print without new line
print('a', end='')
print('b', end='')
print('c', end='')
print()

'''
abc
'''

print("""\
This is a
multiline
string""")

print('Let\'s join '
'the string '
'together')

print(3 * 'ha') #'hahaha'

concatenatedString = "con" + "ca" + "te" + "nated"
print(concatenatedString)

word = 'hello world'

#first character
print(word[0])

#last character
print(word[-1])

#slice
print(word[1:5]) #ello

#first 5 characters
print(word[:5]) #hello

#last 5 characters
print(word[-5:]) #world

#IndexError: string index out of range
#print(word[100])

#Error. strings are immutable
#word[0]= 'a'

#The length of string
print(len(word)) #11

Collection Types

Lists

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
list = [1, 3, 5, 7, 9, 11]

#The third item
print(list[2]) #5

#slice
sublist = list[3:]
print(sublist) #[7, 9, 11]

#concat
list2 = sublist + [13, 15, 18]
print(list2) #[7, 9, 11, 13, 15, 18]

#update item
list2[-1] = 17
print(list2) #[7, 9, 11, 13, 15, 17]

#append item
list2.append(19)
print(list2) #[7, 9, 11, 13, 15, 17, 19]

#assignment to slice
list2[2:5] = ['a']
print(list2) #[7, 9, 'a', 17, 19]

#length of list
print(len(list2)) #5

#loop through the list and retrieve index and value
for i, v in enumerate(list2):
print(i, v) #0 7\n1 9\n2 a\n3 17\n4 19

#2D list
nested_list = [[1, 2, 3], [4, 5, 6]]
print(nested_list[1][1]) #5
1
2
3
#Using list comprehensions to create a list
squares = [x**2 for x in range(10) if x>5]
print(squares) #[36, 49, 64, 81]

Tuple

1
2
3
4
5
aTuple = 'hello', 'world', 1234
print(aTuple) #('hello', 'world', 1234)
print(aTuple[1]) #world
a, b, c = aTuple #unpacking tuple
print(a, b, c) #hello world 1234

Sets

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#A set is an unordered collection with no duplicate elements
x = {'one', 'two', 'three'}
print('two' in x) # True
print('four' in x) # False
print(len(x))
x.add('four')
print(len(x)) #4
x.remove('one')
print(len(x)) #3

for i, n in enumerate(x):
print('#%d: %s' % (i, n))

#0: three
#1: two
#2: four

Dictionary

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
dict = { 'one': 1, 'two': 2 }
dict['three'] = 3
dict['four'] = 4
dict['five'] = 5
print(dict) #{'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5}
del dict['two']
print(dict) #{'one': 1, 'three': 3, 'four': 4, 'five': 5}
print(list(dict)) #['one', 'three', 'four', 'five']
print(sorted(dict)) #['five', 'four', 'one', 'three']
print('three' in dict) #True
print('three1' in dict) #False

for k, v in dict.items(): #iterate
print(k, v)

dict_comprehension = {x: x**2 for x in (2, 4, 6)}
print(dict_comprehension) #{2: 4, 4: 16, 6: 36}

Control Flow

if statement

1
2
3
4
5
6
7
8
9
10
11
12
x = 1

if x < 0:
print('negative')
elif x == 0:
print('zero')
elif x == 1:
print('one')
else:
print('greater than one')

#Python doesn't have switch...case statement
1
2
3
4
5
6
7
8
9
10
foo = 'abc'
bar = '123'
hello = 'world'

if foo == 'abc' and bar == '234':
print('and')
if foo == 'abc' or bar == '234':
print('or')
if not(bar == '234'):
print('not')
1
2
3
4
text = 'Y'

if text in ('y', 'Y', 'yes'):
print('the text is y/Y/yes')

for loop

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
list = [1, 3, 5, 7, 9, 11, 13]

#iterate over all items
for i in list:
print(i)


#range
print(range(3)) #0, 1, 2, 3
print(range(4, 7)) #4, 5, 6, 7
#range with step
print(range(0, 10, 3)) #0, 3, 6, 9

#using range() for indexing
for i in range(4, len(list)): #range(4, 7)
print(i, list[i], sep=',')

'''
4,9
5,11
6,13
'''

#break
for i in range(len(list)):
print(list[i])
if i > 2:
break

'''
1
3
5
7
'''

#continue
for i in range(len(list)):
print(list[i])
if i < 2:
continue
else:
break

'''
1
3
5
'''

#else on loop
for i in range(len(list)):
print(list[i])
else:
print('exhaustion of the list. no break occurs'))

while loop

1
2
3
4
5
6
7
i = 1
sum = 0
while i <= 10:
sum += i
i += 1

print(sum) #55

pass statement

1
2
3
4
5
class MyEmptyClass:
pass

def someFunc():
pass # Remember to implement this!

Functions

1
2
3
4
5
6
7
8
9
def factorial(n):    #return n!
i = 1
s = 1
while i <= n:
s = s * i
i = i + 1
return s

print(factorial(4)) #24
1
2
3
4
5
6
7
8
9
10
11
12
def power(base, index=2): #Default argument value
return base ** index

print(power(3)) #9

#unpacking argument from list
args = [4, 2]
print(power(*args)) #8

#unpacking argument from dictionary
args_dict = { "base": 4, "index": 3 }
print(power(**args_dict)) #64
1
2
3
4
5
#Keyword argument
def keyword_arg_demo(positional_arg, keyword_arg1='1', keyword_arg2='2'):
print(positional_arg, keyword_arg1, keyword_arg2)

keyword_arg_demo('a', keyword_arg2='two') #a 1 two
1
2
3
4
5
6
7
8
9
10
11
#Argument list
def keyword_arg_demo(positional_arg, *more_positional_args, **more_keyword_args):
print(positional_arg)
print("-" * 40)
for arg in more_positional_args: #type(more_positional_args) => <class 'tuple'>
print(arg)
print("-" * 40) #b\n c
for kw in more_keyword_args: #type(more_keyword_args) => <class 'dict'>
print(kw, ":", more_keyword_args[kw]) #more_arg1 : d\n more_arg2 : e

keyword_arg_demo('a', 'b', 'c', more_arg1='d', more_arg2='e')

Lambda expression

1
2
3
pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
pairs.sort(key=lambda pair: pair[1]) #sort by name
print(pairs) #[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]

Modules

1
2
3
4
5
6
#foo.py
def func1():
#...

def func2():
#...
1
2
3
4
5
#bar.py
import foo

foo.func1()
foo.func2()
1
2
3
4
5
#bar.py
from foo import *

func1()
func2()
1
2
3
4
5
#bar.py
from foo import func1 as my_func1, func2

my_func1()
func2()

Classes

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Foo:
class_variable = 'hello'
def __init__(self, data): #constructor
self.instance_variable = data
def bar(self):
return 'hello world'

foo1 = Foo('object 1')
foo2 = Foo('object 2')

Foo.class_variable = 'world'
print(foo1.class_variable) #world
print(foo2.class_variable) #world
print(foo1.instance_variable) #object1
print(foo2.instance_variable) #object2

y = foo1.bar()
print(y) #hello world

More on Python official website