Basics

Fundamentals

Console

print("Hello world!")
name = input("Your name:")
            

Variables

my_var = "My var"
MY_CONSTANT = ''
            

Data Types

type()  # get type
string  # "" ''
int     # 10
float   # 10.5
bool    # True | False
list    # [1, 2] ordered, changeable, dupli
dict    # {'k1': 1} ordered, changeable, no dupli
tuple   # (1, 2) ordered, unchangeable, dupli
set     # {1, 2} unordered, unchangeable, no dupli
bytes   # b'string'
            

Type Conversions

int()   # int(1.5) = 1
float() # float(10) = 10.0
bool()  # bool(10) = True # bool(0) = False
str()   # str(10) = '10'
list()  # list('str') = ['s', 't', 'r']
set()   # set('str') = {'s', 't', 'r'}
tuple() # tuple('str') = ('s', 't', 'r')
# can't convert to dict
            

Static Type Analyzer

MyPy
a: int = 10
def fib(n: int) -> Iterator[int]:
            

Comparisons

==
<=
>=
!=
and
or
            

Conditional

if 1 == 2:
elif 1 == 3:
else:

ternary = "is true" if True else "is false"
            

Logical Operators

+
-
*
/
++ # +1
-- # -1
            

Functions

def name():
  pass

x = lambda a : a + 10 # x(5) = 15 # arrow fn

exit() # kill process
            

*args **kwargs

# args   for list
# kwargs for dict

my_args = ["one", "two"]
my_kwargs = {"k1":"v1","k2":"v2"}

def args_kwargs(*args, **kwargs):
    print(args[0])
    print(kwargs.values())

args_kwargs(*my_args, **my_kwargs)
            

Loops

for..in
for n in range(3):
  print(n) # 0,1,2
            
switch
{0:"zero", 1:"one"}.get(val, "default")
            

Loop Compounds

map()
numbers = [1, 2, 3, 4, 5]
def square(n):
    return n * 2
squared = map(square, numbers)
squared = map(lambda n: n * 2, numbers)
list(squared) # [2, 4, 6, 8, 10]
            
filter()
numbers = [1, 2, 3, 4, 5]
filtered = []
def myFunc(x):
    if x == 3:
        return False
    return True
filtered = filter(myFunc, numbers)
filtered = filter(lambda x: False if x == 3 else True, numbers)
list(filtered) # [1,2,4,5]
            
reduce()
from functools import reduce
numbers = [1, 2, 3, 4, 5]
total = 0
def myFunc(prev, next):
    return prev + next
total = reduce(myFunc, numbers)
total = reduce(lambda x, y: x + y, numbers)
total # 15
            

Advanced

Code Quality

Coding Style

PEP 8

Comments

# Single and multiple lines
            

Packages

PyPi - Package Indexpip - Package Manager

OOP

Classes

class MoneyMachine:
    CURRENCY = "$"

    def __init__(self):
        self.profit = 0

    def add(self, money):
        """Add to profit"""
        self.profit += money

    def report(self):
        """Prints the current profit"""
        print(f"Money: {self.CURRENCY}{self.profit}")

machine = MoneyMachine()
machine.add(10)
machine.report() # Money: $10
            

Modules

# export is default

import math             # import all # math.pi()
from math import *      # import all # pi()
from math import pi, m2 # import some # pi()

import math as m        # import alias # m.pi()
            

Error Handling

1. Create custom exception
class MyCustomException(Exception):
    """My Custom Exception"""
        
2. Raise exception given condition
def my_function(x):
  if not type(x) is int:
    raise MyCustomException("Only integers")
        
3. Handle exception
try:
  my_function("str")
except MyCustomException as e:
  print(str(e))
finally:
  print("The end")
        

Data Types

List

CRUD
list = ["one", "two"] # C
list[0]               # R # get value
list.index('one')     # R # get key
list.insert(0, 'ok')  # U # add el as first
list.append('ok')     # U # add el as last
list[0] = "new"       # U # update value
list.remove('one')    # D #
list.pop(0)           # D # list = ['two']
            
Slicing
list2 = [0,1,2,3,4,5]
list2[2:]             # [2,3,4,5]
list2[:4]             # [0,1,2,3]
list2[::2]            # [0,2,4]
            
Merging
list.extend(['three'])# ['one','two','three']
list += ['three']
            
Extra
len(["one","two"])    # length: 2
list.count('one')     # 1
l2 = list.copy()
list.clear()          # []
list.sort()
list.reverse()
if 'one' in list:     # value exists
            
List Comprehension
fruits = ["apple", "banana", "cherry"]
newlist = []

# this:
for x in fruits:
  if "a" in x:
    newlist.append(x)

# is the same as:
newlist = [x for x in fruits if "a" in x]
            

Int / Float

sum([1,2,3])           # 6
round(1.2)             # 1
random.randint(0, 10)  # random number
            

String

"Hello" + "World"      # Hello World
f"My name is {name}"   # f-String
{:.2f}".format(10)     # 10.00
"string"[2:5]          # rin
" string ".strip()     # string # trimming
"string".split('r')    # ['str','ing']
"str".split()          # ['s', 't', 'r']
"str".replace('r','a') # sta
"UPPER".lower()        # upper
"lower".upper()        # LOWER
            

Data Types

Dict

CRUD
dict = {"k1": "v1"}      # C
dict['k1']               # R # get value
dict.get('k1')           # R # get value
dict.values()            # R # get all values
dict.keys()              # R # get all keys
dict.update({"k2":"v2"}) # U # add item
dict.update({"k1":"11"}) # U # update value
dict.pop("k1")           # D # dict = {"k2:"v2"}
dict.popitem()           # D # removes last item
            
Slicing
# Slicing
# not possible
            
Merging
dict.update({"k3":"v3"})
            
Extra
len(dict)                 # length: 2
d2 = dict.copy()
dict.clear()              # {}
if 'k1' in dict:          # key exists
if 'v1' in dict.values(): # value exists
            

Extra

Date

import datetime
now = datetime.datetime.now()
x = datetime.datetime(2010, 1, 30)
x.strftime("%B") # January
            
Date Format

JSON

import json
my_json = json.loads('{"k1": "one"}')
my_json['k1'] # one
            

RegEx

Exists
import re
search = re.search("ain", "The rain in Spain")
bool(search) # True
            
Length
import re
all = re.findall("ain", "The rain in Spain")
len(list(all)) # 2
            
Replace
import re
sub = re.sub("ain", "ow", "The rain in Spain")
sub # The row in Spow