forked from UWPCE-PythonCert/IntroPython2016a
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmy_for.py
More file actions
50 lines (29 loc) · 795 Bytes
/
my_for.py
File metadata and controls
50 lines (29 loc) · 795 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#!/usr/bin/env python
"""
hand writing 'for'
demonstrates how for interacts with an iterable
"""
l = [1,2,3,4,5,]
def my_for(an_iterable, func):
"""
Emulation of a for loop.
func() will be called with each item in an_iterable
:param an_iterable: anything that satisfies the interation protocol
:param func: a callable -- it will be called, passing in each item
in an_iterable.
"""
# equiv of "for i in l:"
iterator = iter(an_iterable)
while True:
try:
i = next(iterator)
except StopIteration:
break
func(i)
if __name__ == "__main__":
def print_func(x):
print(x)
l = [1,2,3,4,5,]
my_for(l, print_func)
t = ('a','b','c','d')
my_for(t, print_func)