print("Hello world!") name = input("Your name:")
my_var = "My var" MY_CONSTANT = ''
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'
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
a: int = 10 def fib(n: int) -> Iterator[int]:
== <= >= != and or
if 1 == 2: elif 1 == 3: else: ternary = "is true" if True else "is false"
+ - * / ++ # +1 -- # -1
def name(): pass x = lambda a : a + 10 # x(5) = 15 # arrow fn exit() # kill process
# 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)
for n in range(3): print(n) # 0,1,2
{0:"zero", 1:"one"}.get(val, "default")
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]
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]
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
# Single and multiple lines
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
# 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()
class MyCustomException(Exception): """My Custom Exception"""
def my_function(x): if not type(x) is int: raise MyCustomException("Only integers")
try: my_function("str") except MyCustomException as e: print(str(e)) finally: print("The end")
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']
list2 = [0,1,2,3,4,5] list2[2:] # [2,3,4,5] list2[:4] # [0,1,2,3] list2[::2] # [0,2,4]
list.extend(['three'])# ['one','two','three'] list += ['three']
len(["one","two"]) # length: 2 list.count('one') # 1 l2 = list.copy() list.clear() # [] list.sort() list.reverse() if 'one' in list: # value exists
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]
sum([1,2,3]) # 6 round(1.2) # 1 random.randint(0, 10) # random number
"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
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 # not possible
dict.update({"k3":"v3"})
len(dict) # length: 2 d2 = dict.copy() dict.clear() # {} if 'k1' in dict: # key exists if 'v1' in dict.values(): # value exists
import datetime now = datetime.datetime.now() x = datetime.datetime(2010, 1, 30) x.strftime("%B") # JanuaryDate Format
import json my_json = json.loads('{"k1": "one"}') my_json['k1'] # one
import re search = re.search("ain", "The rain in Spain") bool(search) # True
import re all = re.findall("ain", "The rain in Spain") len(list(all)) # 2
import re sub = re.sub("ain", "ow", "The rain in Spain") sub # The row in Spow