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

Lines changed: 40 additions & 0 deletions
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

Lines changed: 39 additions & 0 deletions
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

Lines changed: 12 additions & 0 deletions
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

Lines changed: 27 additions & 0 deletions
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

Lines changed: 16 additions & 0 deletions
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

Lines changed: 29 additions & 0 deletions
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

Lines changed: 14 additions & 0 deletions
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

Lines changed: 29 additions & 0 deletions
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

Lines changed: 11 additions & 0 deletions
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

Lines changed: 15 additions & 0 deletions
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')

0 commit comments

Comments
 (0)