Skip to content

Commit dc7a167

Browse files
committed
add yield sample
1 parent 565993e commit dc7a167

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

py3/advance/do_yield.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
#!/usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
4+
import random, math
5+
6+
def rnd(count):
7+
while count > 0:
8+
count = count - 1
9+
r = random.randint(0, 100)
10+
print('-- random number --')
11+
# 返回随机数r:
12+
yield r
13+
# 代理返回tri(r)的yield,可能有很多次:
14+
ok = yield from tri(r)
15+
# 相当于:
16+
# for x in tri(r):
17+
# yield x
18+
print('-- %s --' % ok)
19+
return 'done'
20+
21+
def tri(r):
22+
yield r * r
23+
yield r * r * r
24+
# 相当于: raise StopIteration('ok')
25+
return 'ok'
26+
27+
def main():
28+
for x in rnd(3):
29+
print(x)
30+
31+
main()

0 commit comments

Comments
 (0)