---
# System prepended metadata

title: python course

---

# python course
## Mark@ucom
### (https://bit.ly/2QgWXW3)

### python
### quit
### pip list
### pip install numpy

### for 4G 32-bit
```
-Xms512m
-Xmx1024m
```

### pip install jupyter

#### demo2 
```
import numpy

l1 = [1, 2, 3]
l2 = [4, 5, 6]
print(type(l1), type(l2))
print(l1 + l2)

a1 = numpy.array(l1)
a2 = numpy.array(l2)
print(type(a1), type(a2))
print(a1 + a2)

```

### demo3
```
mkdir notebook
cd notebook
jupyter-notebook
```

```
jupyter-notebook --generate-config
```

```
c = get_config()
c.NotebookApp.notebook_dir="C:\\Users\\Admin\\notebook"

import webbrowser
webbrowser.register('chrome',None,
    webbrowser.GenericBrowser('C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe'))
c.NotebookApp.browser='chrome'


```

### demo6
```
def fib(n):
    a, b = 0, 1
    while a < n:
        print(a, end=' ')
        a, b = b, a + b
    print()


fib(1000)

```
### About path
```
import sys
print(sys.path)
```
```
>>> import numpy
>>> numpy.__name__
'numpy'
>>> import sys
>>> sys.path
```
```
python demo7.py
```
```
import os
import sys
print(sys.executable)
print(sys.argv)
print(os.getcwd())
```

```
python demo8.py -a -b c=d efg
```

* [https://chromedriver.storage.googleapis.com/index.html?path=78.0.3904.70/](https://chromedriver.storage.googleapis.com/index.html?path=78.0.3904.70/)

```
from selenium.webdriver import Chrome
browser = Chrome()
browser.get("http://www.python.org")
```
```
from selenium.webdriver import Chrome
from selenium.webdriver.common.keys import Keys
import time
browser = Chrome()
browser.get("http://www.python.org")
element1 = browser.find_element_by_name('q')
element1.clear()
element1.send_keys("tensorflow")
element1.send_keys(Keys.RETURN)
time.sleep(10)
browser.close()
```
```
from selenium.webdriver import Chrome
from selenium.webdriver.common.keys import Keys
import time
browser = Chrome()
browser.get("https://shopping.pchome.com.tw/")
element1 = browser.find_element_by_id('keyword')
element1.clear()
element1.send_keys("洗衣粉")
element1.send_keys(Keys.RETURN)
time.sleep(10)
browser.close()
```


```
from selenium.webdriver import Chrome
from selenium.webdriver.common.keys import Keys
import time
browser = Chrome()
browser.get("http://www.python.org")
element1 = browser.find_element_by_name('q')
element1.clear()
element1.send_keys("tensorflow")
element1.send_keys(Keys.RETURN)
result = browser.find_elements_by_css_selector(".list-recent-events.menu")
allItems = result[0].find_elements_by_tag_name("li")
for r in allItems:
    content = r.find_elements_by_tag_name("a")
    print(content[0].text)

#time.sleep(10)
browser.close()

```

```
# Python course
## Last modified:15-Nov-2019

### Install

* Python
* pycharm
* jupyter
```


```
from selenium.webdriver import Chrome
from selenium.webdriver.common.keys import Keys
import time

browser = Chrome()
browser.get("http://www.python.org")
element1 = browser.find_element_by_name('q')
element1.clear()
element1.send_keys("tensorflow")
element1.send_keys(Keys.RETURN)
result = browser. \
    find_element_by_css_selector(".list-recent-events.menu")
allItems = result.find_elements_by_tag_name("li")
for r in allItems:
    content = r.find_elements_by_tag_name("a")
    print(content[0].text)

# time.sleep(10)
browser.close()

```
```
v1 = 0
v2 = 100
v3 = -3000
print(type(v1), type(v2), type(v3))
print(v1+100, v1-100, v1*100, v1/100)
print(2**3, 3**2)
print(2**512)
v4 = 37
print(f"v4 = {v4}, as binary:{v4:b}")
print(f"v4 as Oct = {v4:o}, as hex={v4:x}")
b5 = 0b100
b6 = 0o100
b7 = 0x100
b8 = 100
print(b5, b6, b7, b8)
```
```
from decimal import Decimal

a1 = Decimal(1.5)
print(a1)
a2 = Decimal(1.4)
print(a2)
a3 = Decimal(2.968)
print(a3)
a4 = Decimal('2.968')
print(a4)
a5 = Decimal(2968) * Decimal(0.001) - Decimal(2.968)
print(a5)
a6 = Decimal(2968) * Decimal('0.001') - Decimal('2.968')
print(a6)
from decimal import ROUND_HALF_UP
a7 = Decimal(2.5)
result7 = Decimal(a7.quantize(Decimal(1),
                              rounding=ROUND_HALF_UP))
print(a7, result7)

a8 = Decimal(3.5)
result8 = Decimal(a8.quantize(Decimal(1),
                              rounding=ROUND_HALF_UP))
print(a8, result8)

```

```
from decimal import Decimal

a1 = Decimal(1.5)
print(a1)
a2 = Decimal(1.4)
print(a2)
a3 = Decimal(2.968)
print(a3)
a4 = Decimal('2.968')
print(a4)
a5 = Decimal(2968) * Decimal(0.001) - Decimal(2.968)
print(a5)
a6 = Decimal(2968) * Decimal('0.001') - Decimal('2.968')
print(a6)
from decimal import ROUND_HALF_UP, ROUND_HALF_DOWN, ROUND_HALF_EVEN

digits = [1.5, 2.5, 3.5, 4.5]
rounds = [ROUND_HALF_DOWN, ROUND_HALF_EVEN, ROUND_HALF_UP]
for d in digits:
    for r in rounds:
        result = Decimal(Decimal(d).quantize(Decimal(1),
                                             rounding=r))
        print(f"{d} using {r} ==> {result}")

```
```
a1 = '500'
a2 = '3.14'
a3 = '8-7j'
a4 = 'True'
a5 = 'False'
r1 = int(a1)
print(r1, type(r1))
r2 = float(a2)
print(r2, type(r2))
r3 = float(a1)
print(r3, type(r3))
r4 = complex(a1)
print(r4, type(r4))
r5 = complex(a3)
print(r5, type(r5))
r6 = bool(a4)
r7 = bool(a5)
print(r6, r7, type(r6), type(r7))
```

```
l1 = []
l2 = ['a', 'b']
l3 = list('abc')
l4 = [1, 2, 3, 4]
l5 = [1, 2, 3, 'd', 'e']
l6 = list()
l7 = ['a', 'b', 'c']
lists = [l1, l2, l3, l4, l5, l6]
for l in lists:
    print(type(l), len(l), l)
print(l3 == l7, l3 != l7)
print(l3 == l2, l3 != l2)
print(l3[0] == l2[0]), print(l3[1] != l2[1])
#print(l1[1]) # OOR Error
print(l5[1.0])
t
```
```
list1 = list('ABCDEFG1234567abcdefg')
print(list1[0], list1[len(list1) - 1])
print(list1[-1], list1[-len(list1)])
print(list1[2:6], list1[-5:-2])
print(list1[:5], list1[5:])
print(list1[:-5], list1[-5:])
print(list1[:5], list1[-1:-6:-1])

```

```
list1 = [5, 6, 7]
total = 0
for number in list1:
    total += number
print('total=%d' % total)
list2 = ['apple', 'banana', 'orange','watermelon']
s1 = "today, we have:"
for fruit in list2:
    s1 += "%s," % (fruit)
print(s1)
fruit_length=[]
for f in list2:
    fruit_length.append(len(f))
print(fruit_length)


fruit_length2 = [len(f) for f in list2]
print(fruit_length2)
# part2

```
```
list1 = [5, 6, 7]
total = 0
for number in list1:
    total += number
print('total=%d' % total)
list2 = ['apple', 'banana', 'orange', 'watermelon']
s1 = "today, we have:"
for fruit in list2:
    s1 += "%s," % (fruit)
print(s1)
fruit_length = []
for f in list2:
    fruit_length.append(len(f))
print(fruit_length)
fruit_length2 = [len(f) for f in list2]
print(fruit_length2)
# part2
print('apple' in list2, 'kiwi' in list2)
print('apple' not in list2, 'kiwi' not in list2)
a1, a2, a3, a4 = list2
print(a1, a3, a4, a2)
list2.append('passion fruit')
print(list2)

```
```
l1 = ['red', 'blue']
l2 = ['red', 'blue']
l3 = ['red', 'blue']
# l1.append('brown')
# l2.extend('brown')
# l3 += 'brown'
l1.append(['brown'])
l2.extend(['brown'])
l3 += ['brown']
print(l1)
print(l2)
print(l3)

```
```
a1 = True
a2 = False
b1 = True
b2 = False
b3 = None
b4 = 3.14
b5 = 'hello world'
print(a1 and b1, a1 and b2, a1 and b3, a1 and b4, a1 and b5)
print(a2 and b1, a2 and b2, a2 and b3, a2 and b4, a2 and b5)
print(a1 or b1, a1 or b2, a1 or b3, a1 or b4, a1 or b5)
print(a2 or b1, a2 or b2, a2 or b3, a2 or b4, a2 or b5)

```

```
l1 = list('ABCXZ')
print(l1.index('C'), l1.index('Z'))
#print(l1.index('Q'))
print(l1.count('Q'), l1.count('C'), l1.count('Z'))
l2 = list('ASDFGHJKL')
for l in l2:
    print(l in l1 and l1.index(l), end=', ')
```
```
fruits = [('banana', 60, 30), ('apple', 80, 40), ('kiwi', 50, 99),
          ('melon', 200, 10), ('orange', 30, 20)]
fruits.sort()
print(fruits)
fruits.sort(key=lambda row: row[0])
print(fruits)
fruits.sort(key=lambda r: r[1])
print(fruits)
fruits.sort(key=lambda r: r[2])
print(fruits)

```
```
fruits = [('banana', 60, 30), ('apple', 80, 40),
          ('kiwi', 50, 99),
          ('melon', 200, 10), ('orange', 30, 20)]


def sortByThirdColumn(x):
    return x[2]


fruits.sort()
print(fruits)
fruits.sort(key=lambda row: row[0])
print(fruits)
fruits.sort(key=lambda r: r[1])
print(fruits)
fruits.sort(key=sortByThirdColumn)
print(fruits)


```
```
x1 = 'apple'
x2 = 'banana'
x1, x2 = x2, x1
print(x1, x2)
x3 = 3.14
x4 = None
x3, x4 = x4, x3
print(x3, x4)
v1 = ['a', 'b', 'c']
t1 = ('a', 'b', 'c')
v1.append('d')
print(v1)
# t1.append('d')
t2 = tuple(v1)
v2 = list(t1)
v2.append('d')
print(type(t2), type(v2), v2)

```
```
animals = ['alpaca', 'baboon']


def addAnimal(x):
    x.append('zebra')


print(hex(id(animals)), animals)
addAnimal(animals)
print(hex(id(animals)), animals)
animals2 = ('alpaca', 'baboon')


def addAnimal2(x):
    x += ('zebra',)
    print('inside, x={}'.format(x))

print(hex(id(animals2)), animals2)
addAnimal2(animals2)
print(hex(id(animals2)), animals2)

```
```
animals = ['alpaca', 'baboon']


def addAnimal(x):
    x.append('zebra')


print(hex(id(animals)), animals)
addAnimal(animals)
print(hex(id(animals)), animals)
animals2 = ('alpaca', 'baboon')

y = 3.14
z = 500


def addAnimal2(x):
    x += ('zebra',)
    print('inside, x={},{},{}'.format(x, y, z))
    print(f'inside, x={x},{y},{z}')
    print('inside, x=%s,%f,%d' % (x, y, z))


print(hex(id(animals2)), animals2)
addAnimal2(animals2)
print(hex(id(animals2)), animals2)

```
```
import copy

l1 = list('ABCDE')
l2 = l1
l3 = l1[:]
l4 = list(l1)
print(l1, l2, l3, l4)
l5 = copy.copy(l1)
l6 = copy.deepcopy(l1)
print(l5, l6)
print(hex(id(l1)))
print(hex(id(l5)))
print(hex(id(l6)))
l1[0] = 'a'
l2[1] = 'b'
print(l1, l2, l3)
print(l4, l5, l6)
import numpy

a1 = numpy.array([1, 2, 3, 4, 5])
a2 = a1
a3 = a1.copy()
print(a1, a2, a3)
a1*=2
print(a1, a2, a3)
print(hex(id(a1)))
print(hex(id(a2)))
print(hex(id(a3)))


```
```
import copy

player1 = [['A', 'K'], ['Q', 'J']]
player2 = player1
player3 = copy.copy(player1)
player4 = copy.deepcopy(player1)
print(f"p1:{player1},p2:{player2}")
print(f"p3:{player3},p4:{player4}")
player1.append('JOKER')
print(f"[II]p1:{player1},p2:{player2}")
print(f"[II]p3:{player3},p4:{player4}")
player1[0][0]='10'
print(f"[III]p1:{player1},p2:{player2}")
print(f"[III]p3:{player3},p4:{player4}")
player4[1][1]='8'
print(f"[IV]p1:{player1},p2:{player2}")
print(f"[IV]p3:{player3},p4:{player4}")


```

```
course1 = {'name': 'python', 'instructor': 'mark'}
course2 = {'instructor': 'mark', 'name': 'python'}
print(course1 == course2)
print(course2)
print(course1['name'])
print(course2['instructor'])
course1['duration'] = 20
print(course1)
course3 = dict(name='python', instructor='mark')
print(type(course3), course3)
course4 = dict([('name', 'python'), ('instructor', 'mark')])
print(course4)

```

```
course1 = {'id': 'POOP', 'duration': 30, 'point': 5.5,
           'schedule': ['Saturday', 'Sunday'], 'date': '1-Dec-2019',
           'instructor': '何孟翰'}
print('language' in course1, '何孟翰' in course1, 'id' in course1)

for k in course1:
    print(f'key={k},value={course1[k]}')
print([f'key={k},value={course1[k]}' for k in course1.keys()])

```
```
v1 = ()
print(type(v1))
v2 = []
print(type(v2))
v3 = {}
print(type(v3))

course1 = {'id': 'POOP', 'duration': 30, 'point': 5.5,
           'schedule': ['Saturday', 'Sunday'], 'date': '1-Dec-2019',
           'instructor': '何孟翰'}
print('language' in course1, '何孟翰' in course1, 'id' in course1)

for k in course1:
    print(f'key={k},value={course1[k]}')
print([f'key={k},value={course1[k]}' for k in course1.keys()])
for v in course1.values():
    print(v)
for i in course1.items():
    print(type(i), i)
for i, j in course1.items():
    print(f"key={i},value={j}")
# print(course1['price'])
print(course1.get('price'))

```
```
sales = ['S', 'M', 'L', 'S', 'L', 'M', 'L', 'S', 'L', 'S', 'L', 'M', 'L']
statistics = {}
for r in sales:
    statistics.setdefault(r, 0)
    statistics[r] += 1
print(statistics)
sales2 = [('S', 20), ('M', 30),
          ('L', 15), ('S', 20),
          ('L', 8), ('M', 13),
          ('L', 14), ('S', 9),
          ('L', 15), ('S', 4),
          ('L', 3), ('M', 8), ('L', 12)]
statistics2 = {}
for r, q in sales2:
    statistics2.setdefault(r, 0)
    statistics2[r] += q
print(statistics2)

```

```
class Course:
    def __init__(self, name, duration):
        self.name = name
        self.duration = duration

    def __str__(self):
        return f'[{self.name}]{self.duration}'
    def __repr__(self):
        return f'[{self.name}]{self.duration}'


c1 = Course('POOP', 35)
c2 = c1
c3 = Course('POOP', 35)
c4 = Course('BDPY', 35)
s1 = {c1}
print(type(s1), s1)
s1.add(c2)
print(s1)
s1.add(c3)
print(s1)
s1.add(c4)
print(s1)

```
```
class Course:
    def __init__(self, name, duration):
        self.name = name
        self.duration = duration

    def __eq__(self, other):
        return self.name == other.name and \
               self.duration == other.duration

    def __hash__(self):
        return hash((self.name, self.duration))

    def __str__(self):
        return f'[{self.name}]{self.duration}'

    def __repr__(self):
        return f'[{self.name}]{self.duration}'


c1 = Course('POOP', 35)
c2 = c1
c3 = Course('POOP', 35)
c4 = Course('BDPY', 35)
s1 = {c1}
print(type(s1), s1, hex(hash(c1)))
print(hex(hash(c2)), hex(hash(c3)), hex(hash(c4)))
s1.add(c2)
print(s1)
s1.add(c3)
print(s1)
s1.add(c4)
print(s1)

```
```
def judge(inputScore):
    return 'good' if inputScore >= 80 else 'bad'


scores = [70, 80, 90]
for s in scores:
    print(judge(s))


def judege2(inputScore):
    # (negative, positive)
    return ('bad', 'good')[inputScore >= 80]
for s in scores:
    print(judege2(s))

def judge3(inputScore):
    if inputScore >= 80:
        return 'good'
    else:
        return 'bad'
for s in scores:
    print(judge3(s))

def judge4(x):
    if x >= 90:
        return 'A'
    elif x>=80:
        return 'B'
    elif x>=70:
        return 'C'
    elif x>=60:
        return 'D'
    else:
        return 'fail'
for s in scores:
    print(judge4(s))


```
```
l1 = [3, 1, 4, 5, 9, 24, 15, 30]

sum = 0
for l in l1:
    sum += l
print("sum={}".format(sum))
numbers = [6, -5, 3, -8, 4, -2, 5, -4, 11]
for n in numbers:
    if n < 0:
        numbers.remove(n)
print(numbers)
numbers2 = [6, -5, 3, -8, 4, -2, 5, -4, 11]
for n in numbers2[:]:
    if n < 0:
        numbers2.insert(0, n)
print(numbers2)

```
```
a1 = range(10)
print(a1, type(a1), len(a1), list(a1))
print([x for x in a1])
a2 = range(5, 10)
print([x for x in a2])
a3 = range(50, 100, 2)
print([x for x in a3])

for i in range(10):
    print('*', end="")
print()
for _ in range(10):
    print('*', end='')
print()
import math

a4 = range(0, int(math.pi))
print([x for x in a4])
import numpy

a5 = numpy.arange(10)
print([x for x in a5])
a6 = numpy.arange(0, 1, 0.1)
print([x for x in a6])
a7 = numpy.arange(0, numpy.pi, 0.1)
print([x for x in a7])
a8 = numpy.linspace(0, numpy.pi)
print(len(a8), a8)

```

```
import sys

text = ''

while 1:
    c = sys.stdin.read(1)
    text = text + c
    if c == '\n':
        break
        pass
    pass
print(f'text={text}')

```

```
data1 = [[1, 2, 3, -4, 5],
         [6, 7, 9, 0, 10],
         [1, 3, 5, 7, 9],
         [2, 4, -6, 8, 10]]
for r in data1:
    sum = 0
    for c in r:
        if c < 0:
            print('got an outlier:%d' % c)
            continue
            #break
        #else:
        sum += c
    else:
        print('summation=%d' % sum)

```

```

file1 = open('data\\testfile1','w')
print("this line may exception")
file1.write('write something')
print("file will be closed")
file1.close()
```

```
try:
    file1 = open('data2\\testfile1','w')
    print("this line may exception")
    file1.write('write something')
except FileNotFoundError:
    print("something wrong")
else:
    print("file will be closed")
    file1.close()
print("do something else")
```
```
def divide(x, y):
    try:
        result = x / y
    # except FileNotFoundError:
    except ZeroDivisionError:
        print("divide by zero")
    else:
        print(f"result={result}")
    finally:
        print("calculate finished")


divide(5, 3)
divide(0, 8)
divide(8, 0)
divide(0, 0)
divide('3', '2')

```
```
def myException(level):
    if level < 1:
        raise Exception('reason', 'detail')


try:
    myException(4)
except Exception as e:
    print(f'exception as {e}')
else:
    print('normal execution')

```
```
class MyError(Exception):
    def __init__(self, value):
        self.value = value

    def __str__(self):
        return repr(self.value)

try:
    raise MyError(2 * 2)
except MyError as error:
    print('my error as value=%d' % error.value)

```
```
def something():
    """
    Demo function for help purpose
    :return:
    """
    return 'awesome'
print(something())
print(help(something))
```
```
def outer(num1):
    def inner_increment(x):
        return x + 1

    num2 = inner_increment(num1)
    print(num1, num2)

#inner_increment(40)
outer(50)

```

```
def factorial(number):
    if not isinstance(number, int):
        raise TypeError("Sorry, number should be int")
    if not number >= 0:
        raise ValueError("sorry, number should positive")

    def inner_factorial(number):
        if number <= 1:
            return 1
        return number * inner_factorial(number - 1)

    return inner_factorial(number)
print(factorial(8))

```

```
x = 'global'


def foo():
    print(f'[foo]x={x}')


foo()

y = 'global2'


def bar():
    y = 'local2'
    print(f'[bar]y={y}')


bar()

z = 5


def calculate():
    global z
    #z = 3
    print('[calculate1]z=%d' % z)
    z *= 2
    print('[calculate2]z=%d' % z)


calculate()
print('outside, z=%d'%z)
```
```
x = 'global'


def foo():
    print(f'[foo]x={x}')


foo()

y = 'global2'


def bar():
    y = 'local2'
    print(f'[bar]y={y}')


bar()

z = 5


def calculate():
    global z
    # z = 3
    print('1[calculate]z=%d' % z)
    z *= 2
    print('2[calculate]z=%d' % z)


calculate()
print('outside, z=%d' % z)

p = [5]


def calculate2():
    print('1[calculate2]p=%d' % p[0])
    p[0] *= 2
    print('2[calculate2]p=%d' % p[0])


print('outside, p=%d' % p[0])
calculate2()
print('outside, p=%d' % p[0])


class DemoObject:
    def __init__(self, value):
        self.value = value


q1 = DemoObject(5)


def calculate3(obj):
    print('1[calculate3]q=%d' % obj.value)
    obj.value *= 2
    print('2[calculate3]q=%d' % obj.value)
print('q1.value=%d'%q1.value)
calculate3(q1)
print('q1.value=%d'%q1.value)

```
```
def foo():
    y = "local"
    print('inside y=%s' % y)


foo()
# print(y)
x = 5


def bar():
    x = 10
    print("local x=%d" % x)


bar()
print("x=%d" % x)

```
```
def foo():
    y = "local"
    print('inside y=%s' % y)


foo()
# print(y)
x = 5


def bar():
    x = 10
    print("local x=%d" % x)


bar()
print("x=%d" % x)


def outer():
    x2 = "local"

    def inner():
        nonlocal x2
        x2 = "non local"
        print(f"inner:{x2}")
    print(f"outer1:{x2}")
    inner()
    print(f"outer2:{x2}")
outer()

```
```
import math


def square_root(x):
    return math.sqrt(x)


print(square_root(5))


def square_root2(x): return math.sqrt(x)


print(square_root2(3))

l1 = lambda x: math.sqrt(x)
print(type(l1), l1(5))

```

```
def make_increment(n):
    return lambda x: x + n

print(type(make_increment))
print(type(make_increment(5)))
f = make_increment(10)
print(f(10), f(20))



def make_increment_detail(n):
    def becomeLamda(x):
        return x + n

    return becomeLamda


g = make_increment_detail(10)
print(g(10), g(20))

```
```
def make_increment(n):
    return lambda x: x + n


print(type(make_increment))
print(type(make_increment(5)))
f = make_increment(10)
print(f(10), f(20))


def make_increment_detail(n):
    def becomeLamda(x):
        return x + n

    return becomeLamda


g = make_increment_detail(10)
print(g(10), g(20))


def make_tuple(p):
    return lambda x: (x, 'p' * p)


g2 = make_tuple(5)
print(g2(1), g2(2), g2(3))

```
```
class Counter(object):
    def __init__(self, low, high):
        print('object construct')
        self.current = low
        self.high = high

    def __iter__(self):
        print('prepare to iterate')
        return self

    def __next__(self):
        print('next')
        if self.current > self.high:
            raise StopIteration
        else:
            self.current += 1
            return self.current - 1
c = Counter(1,10)
print(type(c))
print([l for l in c])

```

```
def my_oreo(func):
    def wrapper():
        print("upper side chocolate")
        func()
        print("lower side chocolate")
    return wrapper

def add_filling():
    print("butter_cream!")

get_oreo = my_oreo(add_filling)
get_oreo()
```
```
def my_oreo(func):
    def wrapper():
        print("upper side chocolate")
        func()
        print("---lower side chocolate---")

    return wrapper


def add_regular_filling():
    print("butter_cream!")


def add_peanut():
    print("peanut_butter")


fillings = [add_regular_filling, add_peanut, add_peanut,
            add_regular_filling]
for f in fillings:
    get_oreo = my_oreo(f)
    get_oreo()

```
```
def my_oreo(func):
    def wrapper():
        print("upper side chocolate")
        func()
        print("---lower side chocolate---")

    return wrapper


@my_oreo
def add_regular_filling():
    print("butter_cream!")

add_regular_filling()

```
```
def variable_arguements(fix1, fix2, *args):
    print('fix1={}, fix2={}'.format(fix1, fix2))
    for arg in args:
        print('variable part:{}'.format(arg))
variable_arguements("hello",'world')
variable_arguements('hi','again',300)
variable_arguements('it\'s me','again',300, 3.14, None)
fruits = ['apple','banana','orange']
variable_arguements('buy some','fruit', fruits)
variable_arguements('buy some','fruit', *fruits)

```
```
def my_oreo(func):
    def wrapper(*x):
        print("upper side chocolate")
        func(*x)
        print("---lower side chocolate---")

    return wrapper


@my_oreo
def add_regular_filling(*fills):
    for f in fills:
        print("%s_cream!"%f)

add_regular_filling('cherry')

fillings = ['apple','chocolate','blueberry']
add_regular_filling(*fillings)

```
```
def my_oreo(func):
    def wrapper(x):
        print("upper side chocolate")
        print('filling=%s'%func(x))
        print("---lower side chocolate---")

    return wrapper


@my_oreo
def add_regular_filling(fill):
    return "%s_cream" % fill


add_regular_filling('chocolate')

```

```
import functools
def my_oreo(func):
    @functools.wraps(func)
    def wrapper():
        print("upper side chocolate")
        func()
        print("---lower side chocolate---")

    return wrapper


@my_oreo
def add_regular_filling():
    print("butter_cream!")

print(repr(my_oreo))
print(repr(add_regular_filling))

```
```
def variable_key_value_function(fix, **kwargs):
    print(f'fix part={fix}')
    for k, v in kwargs.items():
        print(f"parameter name={k}, value={v}")


variable_key_value_function("parameter alone")
variable_key_value_function('POOP',name='python programming' )
variable_key_value_function('POOP',name='python programming',
                            duration=35,level='beginning')

```
```
import functools
import time


def timer(func):
    def wrapper_timer(*args, **kwags):
        startTime = time.perf_counter()
        value = func(*args, **kwags)
        endTime = time.perf_counter()
        runTime = endTime - startTime
        print("finished{!r} in {:.4f} seconds".format(
            func.__name__, runTime))
        return value

    return wrapper_timer

```
```
import functools
import time


def timer(func):
    def wrapper_timer(*args, **kwags):
        startTime = time.perf_counter()
        value = func(*args, **kwags)
        endTime = time.perf_counter()
        runTime = endTime - startTime
        print("finished{!r} in {:.4f} seconds".format(
            func.__name__, runTime))
        return value

    return wrapper_timer


@timer
def spend_time_to_calculate(num_times):
    result = 0
    for _ in range(num_times):
        result = sum([i ** 2 for i in range(10000)])
    return result

print(spend_time_to_calculate(1000))
```
```
class Car:
    vendor = 'lexus'
    valid = True
c1 = Car()
c2 = Car()
print(c1.vendor, c2.vendor, Car.vendor)
Car.isImport = True
print(c1.isImport, c2.isImport, Car.isImport)
c1.passenger = 4
c2.color='red'
print(c1.passenger, c1.vendor, c1.valid, c1.isImport)
print(c2.color, c2.vendor, c2.valid, c2.isImport)
c3 = Car()
print(c3.vendor, c3.valid, c3.isImport)

```
```
class Car:
    def __init__(x, speed=0, color=''):
        x.speed = speed
        x.color = color

    def run(self, speed):
        self.speed = speed

    def query(self):
        return self.speed


c1 = Car(90)
print(c1.query())
c1.run(80)
print(c1.query())
c2 = Car()
print(c2.query())
c3 = Car(color='pink')
print(c3.color)
c4 = Car(speed=40)
print(c4.speed, c4.color)
c5 = Car(color='brown', speed=120)
print(c4.speed, c5.color)
```
```
class Car:
    max = 20000

    def __init__(x, speed=0, color=''):
        x.speed = speed
        x.color = color

    def run(self, speed):
        self.speed = speed

    def query(self):
        return self.speed

    @classmethod
    def getMax(cls):
        return cls.max * 0.8

    @staticmethod
    def insuranceRate(year, price):
        return (1 - (0.8 * year)) * price


print(Car.getMax())
print(Car.insuranceRate(2, 200000))
c1 = Car(90)
print(c1.query(), c1.getMax(), c1.max)
c1.run(80)
print(c1.query())
c2 = Car()
print(c2.query())
c3 = Car(color='pink')
print(c3.color)
c4 = Car(speed=40)
print(c4.speed, c4.color)
c5 = Car(color='brown', speed=120)
print(c4.speed, c5.color)

```
```
class Employee(object):
    def __init__(self):
        self.work_content = 'work'

    def doWork(self):
        print('working on %s' % self.work_content)
e1 = Employee()
e1.doWork()
class RD(Employee):
    def doWork(self):
        print("repeat & debug")
rd1 = RD()
rd1.doWork()
class FAE(Employee):
    def doWork(self):
        print("collaborate customers")
fae1 = FAE()
fae1.doWork()
class Scientist(Employee):
    def doWork(self):
        print("build models")
s1 = Scientist()
s1.doWork()
rd2 = RD()
fae2 = FAE()
s2 = Scientist()

```
```

class Employee(object):
    def __init__(self):
        self.work_content = 'work'

    def doWork(self):
        print('working on %s' % self.work_content)


e1 = Employee()
e1.doWork()


class RD(Employee):
    def doWork(self):
        print("repeat & debug")


rd1 = RD()
rd1.doWork()


class FAE(Employee):
    def doWork(self):
        print("collaborate customers")


fae1 = FAE()
fae1.doWork()


class Scientist(Employee):
    def doWork(self):
        print("build models")


s1 = Scientist()
s1.doWork()
rd2 = RD()
fae2 = FAE()
s2 = Scientist()
employees = [rd1, None, 3.14, 'hello world',
             rd2, s1, fae1, s2, fae2]
for e in employees:
    if isinstance(e, Employee):
        e.doWork()



```
```
class Employee(object):
    def __init__(self):
        self.work_content = 'work'

    def doWork(self):
        print('working on %s' % self.work_content)


class RD(Employee):
    def __init__(self):
        self.work_content = "Research*Development"

rd1 = RD()
rd1.doWork()

```
```
import logging


class LoggingDictionary(dict):
    def __setitem__(self, key, value):
        logging.info(f'setting {value} to {key}')
        super().__setitem__(key, value)
logging.basicConfig(filename='logs\\demo83.log',
                    level=logging.INFO)
l1 = LoggingDictionary()
l1['ken']='iOS'
l1['frank']='oracle'
print(l1)

```
```
from collections import UserList


class MyOwnList(UserList):
    def __setitem__(self, key, value):
        if key == len(self.data):
            self.data.append(value)
        else:
            self.data[key] = value

    def square(self):
        for key in range(0, len(self.data)):
            self.data[key] = self.data[key] ** 2


l1 = MyOwnList()

for p in range(10):
    l1[p] = 2 * p
l1.square()
print(l1)

```

from collections import UserDict


class MyOwnDict(UserDict):
    def __init__(self, data={}, **kwargs):
        super().__init__()
        self.update(data)
        self.update(kwargs)

    def __add__(self, other):
        self.data.update(other)
        return self


x1 = {'name': 'pyoo'}
x2 = {'duration': 35}
# print(x1+x2)

y1 = MyOwnDict(codeName='PYOO')
y2 = MyOwnDict(duration=35)
y3 = MyOwnDict(instructor='MarkHo')
y4 = MyOwnDict(recommand={'follow': "BDPY"})
print(y1)
print(y1 + y2)
print(y1+y2+y3)
print(y1+y2+y3+y4)
```

```

from abc import ABC, abstractmethod
class A1(ABC):
    def __init__(self, value):
        super().__init__()
        self.value = value
        pass
    @abstractmethod
    def doSomething(self):
        pass
class B1(A1):
    def doSomething(self):
        print('value={}'.format(self.value))

b1 = B1(300)
#a1 = A1(400)
print(type(b1),)
b1.doSomething()
```
```
class SimpleMeta(type):
    #def __new__(cls, *args, **kwargs):
    def __new__(cls, className, superClasses,
                attributeDict):
        print(f"類別名稱是:{className}")
        print(f'父類別是:{superClasses}')
        print(f"其餘屬性:{attributeDict}")
        return type.__new__(cls, className,superClasses,
                            attributeDict)
class S:
    def __init__(self, name, age):
        self.name = name
        self.age = age

s1 = S('James',20)
print(type(s1), s1.__class__, s1.__class__.__bases__)
print(s1.name, s1.age)
```
```
class SimpleMeta(type):
    # def __new__(cls, *args, **kwargs):
    def __new__(cls, className, superClasses,
                attributeDict):
        print(f"類別名稱是:{className}")
        print(f'父類別是:{superClasses}')
        print(f"其餘屬性:{attributeDict}")
        return type.__new__(cls, className, superClasses,
                            attributeDict)


class S:
    def __init__(self, name, age):
        self.name = name
        self.age = age
class A(S, metaclass=SimpleMeta):
    pass

s1 = S('James', 20)
print(type(s1), s1.__class__, s1.__class__.__bases__)
print(s1.name, s1.age)
print('now, will prepare a1')
a1 = A('Mark', 43)
print('now, a1 generated')
print(a1.name, a1.age)
print(type(a1), a1.__class__, a1.__class__.__bases__)

```
```
class SimpleMeta(type):
    # def __new__(cls, *args, **kwargs):
    def __new__(cls, className, superClasses,
                attributeDict):
        print(f"類別名稱是:{className}")
        print(f'父類別是:{superClasses}')
        print(f"其餘屬性:{attributeDict}")
        return type.__new__(cls, className, superClasses,
                            attributeDict)
    def __call__(self, *args, **kwargs):
        print('parameter passed in:')
        for a in args:
            print(a)
        return super().__call__(*args, **kwargs)


class S:
    def __init__(self, name, age):
        print("init in S")
        self.name = name
        self.age = age


class A(S, metaclass=SimpleMeta):
    pass


a1 = A("Mark", 43)

```

```
class SimpleMeta(type):
    # def __new__(cls, *args, **kwargs):
    def __new__(cls, className, superClasses,
                attributeDict):
        print(f"類別名稱是:{className}")
        print(f'父類別是:{superClasses}')
        print(f"其餘屬性:{attributeDict}")
        return type.__new__(cls, className, superClasses,
                            attributeDict)
    def __call__(self, *args, **kwargs):
        print('parameter passed in:')
        for a in args:
            print(a)
        return super().__call__(*args, **kwargs)


class S:
    def __init__(self, name, age):
        print("init in S")
        print("customize in S")
        self.name = name
        self.age = age


class A(S, metaclass=SimpleMeta):
    def __init__(self, name, age):
        print("init in A")
        super().__init__(name, age)
        print("customize in A")
        pass

a1 = A("Mark", 43)
#a1 = A()
#print(a1.name, a1.age)

```
```
class MetaSingleton(type):
    _instances = {}

    def __call__(self, *args, **kwargs):
        print('inside metaclass singleton')
        if self not in self._instances:
            print("object not yet created")
            print("create one")
            self._instances[self] = \
                super().__call__(*args, **kwargs)
        print('return instance')
        return self._instances[self]


class SingletonClass(metaclass=MetaSingleton):
    def __init__(self):
        print(f'SC id={hex(id(self))}')


x1 = SingletonClass()
x2 = SingletonClass()
print(x1==x2, hex(id(x1)), hex(id(x2)))
```
```
class SingletonParent(object):
    _instance = None

    def __init__(self):
        print('init is called')

    def __new__(cls, *args, **kwargs):
        print('new is called')
        if not cls._instance:
            cls._instance = object.__new__(cls, *args, **kwargs)
        return cls._instance
class SingleClass(SingletonParent):
    pass
s1 = SingleClass()
s2 = SingleClass()
print(hex(id(s1)), hex(id(s2)), s1 == s2)
class NormalClass():
    pass
s3 = NormalClass()
s4 = NormalClass()
print(hex(id(s3)), hex(id(s4)), s3 == s4)

```
```
output1 = open("data\\output1.txt", 'w')
linesToWrite = ["Hi, I am Mark\n","I would like to re-write"]
output1.writelines(linesToWrite)
output1.close()


for _ in range(50):
    output2 = open('data\\output2.txt', 'a')
    nextLines = ['\n add something']
    output2.writelines(nextLines)
    output2.close()
```

```
import glob
import os

paths = 'c:/windows'
print(paths)
allDirs = os.path.join(paths, '*/*.dll')
print(allDirs)
```
```
import glob
import os

paths = 'c:/windows'
print(paths)
allDirs = os.path.join(paths, '*/*.dll')
print(allDirs)
for dll in glob.glob(allDirs):
    print(dll)
```
```
import os

myPath = "c:/windows/system32"

for currentFolder, subFolders, fileNames in os.walk(myPath):
    print(currentFolder, subFolders)
    for f in fileNames:
        print('F', os.path.join(currentFolder, f))

```
```
photos = ['data\\photo1.png',
          'data\\photo2.png',
          'data\\photo3.png']
archives = ['data\\rar1.rar',
            'data\\rar2.rar',
            'data\\rar3.rar']
for photo in archives:
    file1 = open(photo, "rb")
    index = 1
    byte = file1.read(1)
    while byte != "" and index < 9:
        x = int.from_bytes(byte, byteorder='little')
        print('%d,%s' % (index, str(hex(x))))
        byte = file1.read(1)
        index += 1
    print('--------')
    file1.close()

```
```
https://www.moea.gov.tw/MNS/populace/news/NewsRSSdetail.aspx?Kind=1
```

```
import urllib.request
import xml.dom.minidom
file1 = urllib.request.urlopen('https://www.moea.gov.tw/MNS/populace/news/NewsRSSdetail.aspx?Kind=1')
DOMTree = xml.dom.minidom.parse(file1)
file1.close()
type(DOMTree)
collection = DOMTree.documentElement
if collection.hasAttribute("schemaLocation"):
    print(f'schemaLocation={collection.getAttribute("schemaLocation")}')
    
    
```
```
items = collection.getElementsByTagName("item")
for item in items:
    title = item.getElementsByTagName('link')
    print(title[0].childNodes[0].data)
```
```
items = collection.getElementsByTagName("item")
for item in items:
    title = item.getElementsByTagName('link')
    print(title[0].childNodes[0].data)
    description = item.getElementsByTagName('description')
```
```
import unittest


def fun(x):
    return x + 1


class MyTest1(unittest.TestCase):
    def setUp(self):
        print('prepare data')
    def tearDown(self):
        print('store record')
    def test1(self):
        print('test1...')
        self.assertEqual(fun(3), 4)
    @unittest.skip("bug #31245")
    def test2(self):
        print('test2...')
        self.assertEqual(fun(-1),1)

if __name__ == '__main__':
    unittest.main()
```
```
import doctest

def square(x):
    """return square of x.
    >>> square(4)
    16
    >>> square(2)
    4

    :param x:
    :return:
    """
    return x*x

if __name__ == '__main__':
    doctest.testmod()
```
```
def getDigit(x):
    returnDigit = 0
    while x > 0:
        x = x // 10
        returnDigit += 1
    return returnDigit
print(getDigit(1024))
print(getDigit(65536))
print(getDigit(10))

```
```
import multiprocessing
import time
def worker():
    print('start to run')
    time.sleep(2)
    print('run finished')
    return

if __name__ == '__main__':
    jobs = []
    for i in range(5):
        print(f'now execute part:{i}')
        p = multiprocessing.Process(target=worker)
        jobs.append(p)
        p.start()
    print('result=',jobs)
    time.sleep(3)
    print('result=', jobs)

```
```
import multiprocessing
import time
def worker(num):
    print('worker pass parameter as:', num)
    time.sleep(4)
    print('worker finished as:{}'.format(num))
    return

if __name__ == '__main__':
    jobs = []
    for i in range(5):
        p = multiprocessing.Process(target=worker, args=(i,))
        jobs.append(p)
        p.start()
    print("jobs=",jobs)

```
```
pip install pygetwindow
pip install pyautogui
```
```
import pyautogui

print(pyautogui.size())
for i in range(10):
    pyautogui.moveTo(100 + 10 * i, 100 + 10 * i, duration=1)
    pyautogui.moveTo(200 + 10 * i, 100 + 10 * i, duration=1)
    pyautogui.moveTo(200 + 10 * i, 200 + 10 * i, duration=1)
    pyautogui.moveTo(100 + 10 * i, 200 + 10 * i, duration=1)

```
```

import multiprocessing
import time


def worker():
    name = multiprocessing.current_process().name
    print('[%s] start' % name)
    time.sleep(4)
    print('[%s] stop' % name)

def my_service():
    name = multiprocessing.current_process().name
    print('[%s] start' % name)
    time.sleep(6)
    print('[%s] stop' % name)

if __name__ == '__main__':
    service = multiprocessing.Process(name='bg service',
                                      target=my_service)
    s1 = multiprocessing.Process(name='worker 1', target= worker)
    s2 = multiprocessing.Process(target = worker)
    s1.start()
    s2.start()
    service.start()```
    
```
import multiprocessing
import time
import random

def daemon():
    name = multiprocessing.current_process().name
    print("[%s] start work" % name)
    time.sleep(random.randint(1,10))
    print("[%s] stop work" % name)


if __name__ == '__main__':
    d = multiprocessing.Process(name='daemon', target=daemon)
    d.daemon = True
    print('prepare start')
    d.start()
    d.join()
    print('program terminated')

```
```
import multiprocessing
import time
import random
from datetime import datetime
def daemon():
    name = multiprocessing.current_process().name
    print(f"({datetime.now()})[{name}] start work")
    time.sleep(random.randint(1,10))
    print(f"({datetime.now()})[{name}] stop work")


if __name__ == '__main__':
    d = multiprocessing.Process(name='daemon', target=daemon)
    d.daemon = True
    print(f'({datetime.now()})prepare start')
    d.start()
    d.join()
    print(f'({datetime.now()})program terminated')

```
```
import multiprocessing
import time


def D1():
    name = multiprocessing.current_process().name
    print(f'[{name}]start')
    time.sleep(2)
    print(f'[{name}]stop')


def ND1():
    name = multiprocessing.current_process().name
    print(f'[{name}]start')
    time.sleep(1.5)
    print(f'[{name}]stop')


if __name__ == '__main__':
    d = multiprocessing.Process(name='daemon', target=D1)
    d.daemon = True
    n = multiprocessing.Process(name='non daemon', target=ND1)
    n.daemon = False
    print(f'd is alive?{d.is_alive()}, n is alive?{n.is_alive()}')
    d.start()
    n.start()
    print(f'd is alive?{d.is_alive()}, n is alive?{n.is_alive()}')


```
import multiprocessing
import time


def D1():
    name = multiprocessing.current_process().name
    print(f'[{name}]start')
    time.sleep(5)
    print(f'[{name}]stop')


def ND1():
    name = multiprocessing.current_process().name
    print(f'[{name}]start')
    time.sleep(1.5)
    print(f'[{name}]stop')


if __name__ == '__main__':
    d = multiprocessing.Process(name='daemon', target=D1)
    d.daemon = True
    n = multiprocessing.Process(name='non daemon', target=ND1)
    n.daemon = False
    print(f'd is alive?{d.is_alive()}, n is alive?{n.is_alive()}')
    d.start()
    n.start()
    print(f'd is alive?{d.is_alive()}, n is alive?{n.is_alive()}')
    d.join(1)
    print(f'd is alive?{d.is_alive()}, n is alive?{n.is_alive()}')
    time.sleep(1)
    n.join()
    print(f'd is alive?{d.is_alive()}, n is alive?{n.is_alive()}')
    d.terminate()
    n.terminate()
    time.sleep(1)
    print(f'd is alive?{d.is_alive()}, n is alive?{n.is_alive()}')




```