Skip to content

Commit 65d4da6

Browse files
committed
add samples
1 parent b8b4686 commit 65d4da6

File tree

104 files changed

+2239
-0
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

104 files changed

+2239
-0
lines changed

samples/advance/do_generator.py

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
#!/usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
4+
s = (x * x for x in range(5))
5+
print(s)
6+
for x in s:
7+
print(x)
8+
9+
def fib(max):
10+
n, a, b = 0, 0, 1
11+
while n < max:
12+
yield b
13+
a, b = b, a + b
14+
n = n + 1
15+
return 'done'
16+
17+
f = fib(10)
18+
print('fib(10):', f)
19+
for x in f:
20+
print(x)
21+
22+
# call generator manually:
23+
g = fib(5)
24+
while 1:
25+
try:
26+
x = g.send(None)
27+
print('g:', x)
28+
except StopIteration as e:
29+
print('Generator return value:', e.value)
30+
break
31+
32+
# call generator using iter:
33+
i = iter(fib(5))
34+
while 1:
35+
try:
36+
r = next(i)
37+
print('i:', r)
38+
except StopIteration as e:
39+
print('Generator return value:', e.value)
40+
break

samples/advance/do_iter.py

+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
#!/usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
4+
from collections import Iterable
5+
print('iterable? [1, 2, 3]:', isinstance([1, 2, 3], Iterable))
6+
print('iterable? \'abc\':', isinstance('abc', Iterable))
7+
print('iterable? 123:', isinstance(123, Iterable))
8+
9+
# iter list:
10+
print('iter [1, 2, 3, 4, 5]')
11+
for x in [1, 2, 3, 4, 5]:
12+
print(x)
13+
14+
d = {'a': 1, 'b': 2, 'c': 3}
15+
16+
# iter each key:
17+
print('iter key:', d)
18+
for k in d.keys():
19+
print('key:', k)
20+
21+
# iter each value:
22+
print('iter value:', d)
23+
for v in d.values():
24+
print('value:', v)
25+
26+
# iter both key and value:
27+
print('iter item:', d)
28+
for k, v in d.items():
29+
print('item:', k, v)
30+
31+
# iter list with index:
32+
print('iter enumerate([\'A\', \'B\', \'C\']')
33+
for i, value in enumerate(['A', 'B', 'C']):
34+
print(i, value)
35+
36+
# iter complex list:
37+
print('iter [(1, 1), (2, 4), (3, 9)]:')
38+
for x, y in [(1, 1), (2, 4), (3, 9)]:
39+
print(x, y)

samples/advance/do_listcompr.py

+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
#!/usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
4+
print([x * x for x in range(1, 11)])
5+
print([x * x for x in range(1, 11) if x % 2 == 0])
6+
print([m + n for m in 'ABC' for n in 'XYZ'])
7+
8+
d = {'x': 'A', 'y': 'B', 'z': 'C' }
9+
print([k + '=' + v for k, v in d.items()])
10+
11+
L = ['Hello', 'World', 'IBM', 'Apple']
12+
print([s.lower() for s in L])

samples/advance/do_prod_cons.py

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
#!/usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
4+
import time
5+
6+
def consumer():
7+
r = ''
8+
while True:
9+
n = yield r
10+
if not n:
11+
return
12+
print('[CONSUMER] Consuming %s...' % n)
13+
time.sleep(1)
14+
r = '200 OK'
15+
16+
def produce(c):
17+
c.send(None)
18+
n = 0
19+
while n < 5:
20+
n = n + 1
21+
print('[PRODUCER] Producing %s...' % n)
22+
r = c.send(n)
23+
print('[PRODUCER] Consumer return: %s' % r)
24+
c.close()
25+
26+
c = consumer()
27+
produce(c)

samples/advance/do_slice.py

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
#!/usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
4+
L = ['Michael', 'Sarah', 'Tracy', 'Bob', 'Jack']
5+
6+
print('L[0:3] =', L[0:3])
7+
print('L[:3] =', L[:3])
8+
print('L[1:3] =', L[1:3])
9+
print('L[-2:] =', L[-2:])
10+
11+
R = list(range(100))
12+
print('R[:10] =', R[:10])
13+
print('R[-10:] =', R[-10:])
14+
print('R[10:20] =', R[10:20])
15+
print('R[:10:2] =', R[:10:2])
16+
print('R[::5] =', R[::5])

samples/advance/do_yield.py

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
#!/usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
4+
def each_ascii(s):
5+
for ch in s:
6+
yield ord(ch)
7+
return '%s chars' % len(s)
8+
9+
def yield_from(s):
10+
r = yield from each_ascii(s)
11+
print(r)
12+
13+
def main():
14+
for x in each_ascii('abc'):
15+
print(x) # => 'a', 'b', 'c'
16+
it = each_ascii('xyz')
17+
try:
18+
while True:
19+
print(next(it)) # => 'x', 'y', 'z'
20+
except StopIteration as s:
21+
print(s.value) # => '3 chars'
22+
23+
# using yield from in main() will change main() from function to generator:
24+
# r = yield from each_ascii('hello')
25+
26+
for ch in yield_from('hello'):
27+
pass
28+
29+
main()

samples/async/async_hello.py

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
#!/usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
4+
import asyncio
5+
6+
@asyncio.coroutine
7+
def hello():
8+
print("Hello world!")
9+
yield from asyncio.sleep(1)
10+
print("Hello again!")
11+
12+
loop = asyncio.get_event_loop()
13+
loop.run_until_complete(hello())
14+
loop.close()

samples/async/async_wget.py

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
#!/usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
4+
import threading
5+
import asyncio
6+
7+
@asyncio.coroutine
8+
def wget(host):
9+
print('wget %s...' % host)
10+
print('current thread: %s' % threading.current_thread())
11+
connect = asyncio.open_connection(host, 80)
12+
reader, writer = yield from connect
13+
header = 'GET / HTTP/1.0\r\nHost: %s\r\n\r\n' % host
14+
writer.write(header.encode('utf-8'))
15+
yield from writer.drain()
16+
while True:
17+
line = yield from reader.readline()
18+
if line == b'\r\n':
19+
break
20+
print('%s header > %s' % (host, line.decode('utf-8').rstrip()))
21+
# Ignore the body, close the socket
22+
writer.close()
23+
24+
loop = asyncio.get_event_loop()
25+
tasks = [asyncio.async(wget(host)) for host in ['www.sina.com.cn', 'www.sohu.com', 'www.163.com']]
26+
for task in tasks:
27+
loop.run_until_complete(task)
28+
loop.close()
29+
print('main thread: %s' % threading.current_thread())

samples/basic/do_for.py

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
#!/usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
4+
# 打印list:
5+
names = ['Michael', 'Bob', 'Tracy']
6+
for name in names:
7+
print(name)
8+
9+
# 打印数字 0 - 9
10+
for x in range(10):
11+
print(x)

samples/basic/do_if.py

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
#!/usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
4+
# 注意:
5+
# input()返回的是字符串
6+
# 必须通过int()将字符串转换为整数
7+
# 才能用于数值比较:
8+
age = int(input('Input your age: '))
9+
10+
if age >= 18:
11+
print('adult')
12+
elif age >= 6:
13+
print('teenager')
14+
else:
15+
print('kid')

samples/basic/do_input.py

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
#!/usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
4+
name = input()
5+
print('Hello,', name)

samples/basic/do_print.py

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
#!/usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
4+
print('The quick brown fox', 'jumps over', 'the lazy dog')
5+
print(300)
6+
print(100 + 200)
7+
print('100 + 200 =', 100 + 200)

samples/basic/do_while.py

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
#!/usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
4+
# 计算1+2+3+...+100:
5+
sum = 0
6+
n = 1
7+
while n <= 100:
8+
sum = sum + n
9+
n = n + 1
10+
print(sum)

samples/basic/hello.py

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
#!/usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
4+
print('Hello, world')

samples/basic/the_dict.py

+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
#!/usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
4+
d = {
5+
'Michael': 95,
6+
'Bob': 75,
7+
'Tracy': 85
8+
}
9+
print('d[\'Michael\'] =', d['Michael'])
10+
print('d[\'Bob\'] =', d['Bob'])
11+
print('d[\'Tracy\'] =', d['Tracy'])
12+
print('d.get(\'Thomas\', -1) =', d.get('Thomas', -1))

samples/basic/the_list.py

+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
#!/usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
4+
classmates = ['Michael', 'Bob', 'Tracy']
5+
print('classmates =', classmates)
6+
print('len(classmates) =', len(classmates))
7+
print('classmates[0] =', classmates[0])
8+
print('classmates[1] =', classmates[1])
9+
print('classmates[2] =', classmates[2])
10+
print('classmates[-1] =', classmates[-1])
11+
classmates.pop()
12+
print('classmates =', classmates)

samples/basic/the_set.py

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
#!/usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
4+
s1 = set([1, 1, 2, 2, 3, 3])
5+
print(s1)
6+
s2 = set([2, 3, 4])
7+
print(s1 & s2)
8+
print(s1 | s2)

samples/basic/the_string.py

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
#!/usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
4+
s = 'Python-中文'
5+
print(s)
6+
b = s.encode('utf-8')
7+
print(b)
8+
print(b.decode('utf-8'))

samples/basic/the_tuple.py

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
#!/usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
4+
classmates = ('Michael', 'Bob', 'Tracy')
5+
print('classmates =', classmates)
6+
print('len(classmates) =', len(classmates))
7+
print('classmates[0] =', classmates[0])
8+
print('classmates[1] =', classmates[1])
9+
print('classmates[2] =', classmates[2])
10+
print('classmates[-1] =', classmates[-1])
11+
12+
# cannot modify tuple:
13+
classmates[0] = 'Adam'

samples/commonlib/check_bmp.py

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
#!/usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
4+
import struct
5+
6+
bmp_header = b'\x42\x4d\x38\x8c\x0a\x00\x00\x00\x00\x00\x36\x00\x00\x00\x28\x00\x00\x00\x80\x02\x00\x00\x68\x01\x00\x00\x01\x00\x18\x00'
7+
8+
print(struct.unpack('<ccIIIIIIHH', bmp_header))

samples/commonlib/do_base64.py

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
#!/usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
4+
import base64
5+
6+
s = base64.b64encode('在Python中使用BASE 64编码'.encode('utf-8'))
7+
print(s)
8+
d = base64.b64decode(s).decode('utf-8')
9+
print(d)
10+
11+
s = base64.urlsafe_b64encode('在Python中使用BASE 64编码'.encode('utf-8'))
12+
print(s)
13+
d = base64.urlsafe_b64decode(s).decode('utf-8')
14+
print(d)

samples/commonlib/use_collections.py

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
#!/usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
4+
from collections import namedtuple
5+
6+
Point = namedtuple('Point', ['x', 'y'])
7+
p = Point(1, 2)
8+
print('Point:', p.x, p.y)
9+
10+
from collections import deque
11+
12+
q = deque(['a', 'b', 'c'])
13+
q.append('x')
14+
q.appendleft('y')
15+
print(q)
16+
17+
from collections import defaultdict
18+
19+
dd = defaultdict(lambda: 'N/A')
20+
dd['key1'] = 'abc'
21+
print('dd[\'key1\'] =', dd['key1'])
22+
print('dd[\'key2\'] =', dd['key2'])
23+
24+
from collections import Counter
25+
c = Counter()
26+
for ch in 'programming':
27+
c[ch] = c[ch] + 1
28+
print(c)

0 commit comments

Comments
 (0)