’ ‘ can be used instead of “ “
Datatypes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| x = 'Hello World' #str
x = 20 #int
x = 20.5 #float
x = 1j #complex
x = ['apple', 'banana', 'cherry'] #list
x = ('apple', 'banana', 'cherry') #tuple
x = range(6) #range
x = {'name': 'John', 'age': 36} #dict
x = {'apple', 'banana', 'cherry'} #set
x = frozenset({'apple', 'banana', 'cherry'}) #rozenset
x = True #bool
x = b'Hello' #bytes
x = bytearray(5) #bytearray
x = memoryview(bytes(5)) #memoryview
|
Operators
Arithmetic
Operator | Name | Example |
---|
+ | Addition | x + y |
- | Subtraction | x - y |
* | Multiplication | x * y |
/ | Division | x / y |
% | Modulus | x % y |
** | Exponentiation | x**y |
// | Floor division | x//y |
Assignment
Operator | Example | Same As |
---|
= | x = 5 | x + y |
+= | x += 5 | x = x + 5 |
-= | x -= 5 | x = x - 5 |
*= | x *= 5 | x = x * 5 |
/= | x /= 5 | x = x / 5 |
%= | x %= 5 | x = x % 5 |
**= | x **= 5 | x = x ** 5 |
//= | x //= 5 | x = x // 5 |
Comparison
Operator | Name | Example |
---|
== | equal to | x == y |
!= | not equal to | x != y |
> | greater than | x > y |
< | less than | x < y |
>= | greater than or equal to | x >= y |
<= | less than or equal to | x <= y |
Logical
Operator | Name | Description | Example |
---|
and | AND | returns true if both statements are true | x < 5 and x < 10 |
or | OR | returns true if one of the statements is true | x < 5 or x < 4 |
not | NOT | reverse the result, returns false if the result is true | not(x < 5 and x < 10) |
Bitwise
Operator | Name | Description | Example |
---|
& | AND | Sets each bit to 1 if both bits are 1 | x & y |
| | OR | Sets each bit to 1 if one of two bits is 1 | x \| y |
^ | XOR | Sets each bit to 1 if only one of two bits is 1 | x ^ y |
~ | NOT | Inverts all the bits | ~x |
« | Zero fill left shift | Shift left by pushing zeros in from the right and let the leftmost bits fall off | x << 2 |
» | Signed right shift | Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off | x >> 2 |
In and Output
1
2
| username = input('Enter username:') #write user input as string in variable
print(f'my name is {username}')
|
Casting
change the data type of a variable
1
2
3
4
5
6
| str(3.0) #convert to string
int(2.8) #convert to int
float('3') #convert to float
int(False) # 0
int(True) # 1
print(type(0)) # <class 'int'>
|
String Operations
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
| a = 'Hello, World!'
list('hello') #returns ['h', 'e', 'l', 'l', 'o']
a[1] #returns the second letter (e)
a[:5] #removes everything after the first 5 letters (Hello)
a[1:] #removes the first letter (ello, World!)
a[2:5] #removes the first 2 letters and the last 5 letters (llo)
a.upper() #sets all letters as upper case
a.lower() #sets all letters as lower case
a.strip() #removes all whitespaces
a.replace('H', 'J') #replase a letter
a.split(',') # returns ['Hello', ' World!']
a.index('H') #returns the index of a character in a string
a.__contains__('llo') #returns true
exec("print('Hello')") #runs string as python code
eval("2+2") #runs string as python expresion
|
eval()
is used to evaluate a string as a python expression, while exec()
is used to evaluate a string as a python statement. They are usefull to convert a string e.g. a function name stored in a config file to a python function name.
Lists
can contain different data types
Array
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
| li = [69, 'banana', True]
print(li)
li[0] #returns the first element
li[-1] # short for: li[len(li)-1] (last element)
len(li) #returns the length
li.insert(2, 'watermelon') #insert an item at index 2
li.append('orange') #append an item at the end
li.remove('banana') #remove an item
li.pop(1) #remove item at index 1
thislist = li.copy() #copy a list
tropical = ['mango', 'pineapple', 'papaya']
li.extend(tropical) #add one list to anouter
li.sort() #sort the actual list (returns None)
li.sort(reverse=True) #sort the list descending
li.reverse() #reverse the list order
tropical.index('mango') #returns the index to a value
list.clear() #clear the list content
del li #delete the entire list
list1 = ['a', 'b', 'c']
list2 = [1, 2, 3]
list3 = list1 + list2 #join two list
print(list3)
# ['a', 'b', 'c', 1, 2, 3]
|
Tuple
a tuple is a final array
1
| eggs = ('hello', 42, 0.5)
|
multiple assignment trick
1
2
| cat = ['fat', 'gray', 'loud']
size, color, disposition = cat
|
short for…
1
2
3
| size = cat[0]
color = cat[1]
disposition = cat[2]
|
Comprehension
1
2
| arr = [i for i in range(10) if i % 2 == 0]
# [0, 2, 4, 6, 8]
|
short for…
1
2
3
4
| arr = []
for i in range(10):
if i % 2 == 0:
arr.append(i)
|
1
2
3
| fruits = ['apple', 'banana', 'cherry', 'kiwi', 'mango']
newlist = [fruit for fruit in fruits if 'a' in fruit]
# ['apple', 'banana', 'mango']
|
short for…
1
2
3
4
| newlist = []
for fruit in fruits:
if 'a' in fruit:
newlist.append(fruit)
|
i
gets added to the array while condition == True
Dictionaries
1
2
3
4
5
6
7
8
9
10
| thisdict = {'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
print(thisdict)
thisdict.get('model') #returns the value of the 'model' key
list(thisdict.keys()) #returns a list of the keys
list(thisdict.values()) #returns a list of all values
thisdict['year'] = 2018 #change a value
thisdict.update({'year': 2020}) #changa/add key:value pair
thisdict.pop('model') #remove an item
mydict = thisdict.copy() #copy the dictionary
dict(sorted(dic.items(), key=lambda item: item[1])) #sort dictionary
|
Flow Control
if else statement
1
2
3
4
5
6
7
8
| a = 200
b = 33
if b > a:
print('b is greater than a')
elif a == b:
print('a and b are equal')
else:
print('a is greater than b')
|
in
can often be used instead of __contains__()
but omly returns True
if the list contains the full strings, while the function returns `True’ even if only a partial string is in the list.
1
2
3
4
| fruits = ['apples', 'oranges', 'bananas']
if 'apples' in fruits:
print('apples are in the list')
|
while loop
1
2
3
4
5
6
7
8
|
i = 0
while i < 6:
i += 1
if i == 3:
continue #restart the loop
print(i) #break to quit the loop
|
for loop
for each
1
2
3
4
5
6
| fruits = ['apple', 'banana', 'cherry']
for item in fruits:
print(item)
for i in range(5): #execute 5 times
print(fruits)
|
match /switch case statement
only supported in python >= 3.10
1
2
3
4
5
6
7
8
| n = 0
match n:
case 0:
print('printed if n = 0')
case 1:
print('printed if n = 1')
case _:
print('printed if none above apply')
|
It works with the following arguments:
(int, float, str, bytes, tuple, list, set, frozenset, dict, range, slice, type)
Functions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
| def my_function(fname, lname):
return f'{fname} {lname}'
my_function('Emil', 'Refsnes')
iterable = [1, 2, 3]
map(my_function, iterable) #executes a specified function for each item in an iterable
x = lambda a: a + 10 #lambda/anonymous function
print(x(5))
var1 = my_function(fname, lname) #run func and store return value
var2 = my_function #set 'alias' for function 'my_function'
print(var(saracen,rhue))
|
Classes
public: standart /items are globaly availible private: 2 underscores at the beginning /items only availible in the current class protected: 1 underscore at the beginning /items only availible in the current class and subclasses
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
| class Person:
def __init__(self, name, age): #constructor //destructor: __del__
self.name = name
self.age = age
def myfunc(self):
print('Hello my name is ' + self.name)
class Student(Person): #Student is a chld class of person
pass #Student inherits the constructor and all methods from person
p1 = Person('John', 36) #create object
print(p1.name)
print(p1.age)
p1.myfunc() #call method
|
Exceptions
1
2
3
4
5
6
7
8
| try:
print(x)
except NameError:
print('Variable x is not defined')
except:
print('Something else went wrong')
finally:
print('The "try except" is finished')
|
File handling
r
open file in read mode
r+
Opens a file for both reading and writing
w
write content/overwrite existing content
w+
Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, it creates a new file for reading and writing
1
2
3
4
5
6
| with open('text.txt', 'w') as f: #open file in write mode and store in f
f.write('Woops! I have deleted the content!') #write content/overwrite existing content
with open('text.txt', 'r') as f: #open file in read mode and store in f
f.read() #returns file content as string
|
File operations
1
2
3
4
| import shutil
shutil.copy('exp.py', 'Kap04/exp.py')
shutil.move('exp.py', 'Kap04/exp.py')
|
sys module
The sys.argv variable is a list in Python, which contains the command-line arguments passed to the script. The first item in this list is the name of the script. The list contains the rest of the arguments passed to the script.
1
2
3
4
| import sys
arguments = sys.argv #returns a list of arguments
arguments.pop(0) #remove the first argument (the script name)
|
os module
1
2
3
4
5
6
7
8
9
10
11
12
| import os
os.listdir('./') #list all files in the current directory
os.system('ls') #run a shell command
os.remove('exp.py') #delete file
os.rmdir('myfolder') #delete folder
os.mkdir('myfolder') #create folder
os.getcwd() #get current working directory
os.chdir('myfolder') #change directory
os.path.exists('myfile.txt') #check if file exists
|
Since you can run shell commands with os.system()
, you can also run bash, nodejs or other python scripts with it.
Keep in mind that every time you use this function, you are using a new shell, so if you have to run multiple commands with the same shell connect them with ` && `
Zip Module
1
2
| import zipfile as zf
from os import system as cmd
|
zip a file
1
2
3
| def zip(file):
zf.ZipFile(file + '.zip', 'w').write(file)
cmd('rm -rf ' + file)
|
unzip a file
1
2
3
| def unzip(file):
zf.ZipFile(file).extractall()
cmd('rm -fr ' + file)
|
backup a folder to a zip file
1
2
| def backup(folder):
zf.ZipFile(folder+'.zip', 'w').write(folder)
|
JSON Module
Save data to file
1
2
3
| dic = {'name': 'John', 'age': 30, 'city': 'New York'}
with open('data.json', 'w') as f:
json.dump(dic, f) #write to file
|
Get data from file
1
2
| with open('data.json', 'r') as f:
data = json.load(f) #read from file
|
Exel Module
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| import openpyxl
import math
wb = openpyxl.Workbook()
sheet = wb.active
sheet.title = 'myTable' #select and name tatable
x, y = 1, 1
for i in range(-31, 31):
sheet.cell(row=y, column=x).value = math.sin(i / 10) #write into field
y += 1
wb.save('table.xlsx') #safe file
|