跳轉到

Features

Different Implementation


flowchart LR
    A[Source Code]-->B[CPython]
    subgraph Cpython Interpreter
    B-->C[CPython Bytecode]
    C-->D[CPython Virtual Machine]
    end
    D-->E[Machine Code]
    A[Source Code]-->F[Jython]
    subgraph Jython Interpreter
    F-->G[Java Bytecode]
    G-->H["Java Virtual Machine (JVM)"]
    end
    H-->E[Machine Code]
    A[Source Code]-->I[IronPython]
    subgraph IronPython Interpreter
    I-->J[.NET Bytecode]
    J-->K["Common Language Runtime (CLR)"]
    end
    K-->E[Machine Code]


Others:

  • PyPy

Types

Tuple

myTuple = (1, 2, 3, 4, 5)
print(myTuple)

List

myList = ["banana", "cherry", "apple"]
i1, *i2, i3 = myList
length = len(myList)
print(length)

Set

mySet = set()
mySet.add(3)
mySet.add(1)
print(len(mySet))

Dictionary

from collections import defaultdict
myDict = defaultdict(int)
myDict['age'] = 20
print(myDict)

Deque

from collections import deque
d = deque([1, 2, 3])
d.appendleft(4)
d.popleft()
print(d)

Counter

from collections import Counter
s = "aabbbcccc"
myCounter = Counter(s)
myCounter.update('de')
print(myCounter)

Random

import random
a = random.random()
b = random.uniform(1, 10)
c = random.randrange(1, 10)
print(c)

myList = list("abcdefg")
a = random.choice(myList)
b = random.sample(myList, 3)
c = random.choices(myList, k=3)  # repeatable

random.shuffle(myList)
print(myList)

Special Keywords

Range

for x in range(1,10,2):
    print(x)

Enumerate

l = ['a','b','c']

for idx, item in enumerate(l):
    print(idx, item)

Lambda

from functools import reduce

a = [1, 2, 3, 4, 5]

b = list(map(lambda x: x * 2, a))
# print(b)
# equals to => b = [elem*2 for elem in a]

c = list(filter(lambda x: x % 2 == 0, a))
# print(c)
# equals to => c = [x for x in a if x % 2 == 0]

d = reduce(lambda x, y: x*y, a)
# print(d)

Zip

nameList = ["david", "john"]
ageList = [20, 30]
for name, age in zip(nameList, ageList):
    print(f"{name}: {age}")
print(list(zip(nameList, ageList)))

Decorator

class StartEndDecorator:
    def __init__(self, func):
        self.func = func

    def __call__(self, *args, **kwargs):
        print('Start')
        result = self.func(*args, **kwargs)
        print('End')
        return result


@StartEndDecorator
def add10(x):
    return x + 10


result = add10(5)
print(result)

class CountCalls:
    def __init__(self, func):
        self.func = func
        self.numCalls = 0

    def __call__(self, *args, **kwargs):
        self.numCalls += 1
        print(f'This is executed {self.numCalls} times')
        return self.func(*args, **kwargs)


@CountCalls
def sayHello():
    print('Hello World')

sayHello()

Generator

def firstn_generator(n):
    num = 0
    while num < n:
        yield num
        num += 1

g = firstn_generator(10)
v = next(g)

for x in firstn_generator(10):
    print(x)

Error Handling

try:
    raise Exception("OMG")
except Exception as err :
    print(err)
with open("file.txt", "w") as file:
    file.write("Hello World")

Reference