In [1]:
from __future__ import print_function
In [2]:
class my_range():
def __init__(self, n):
self.n = n
self.i = 0
def __next__(self):
if self.i < self.n:
self.i += 1
return self.i - 1
else:
raise StopIteration
In [3]:
for i in my_range(3):
print(i, i*i)
In [4]:
for i in iter(my_range(3)):
print(i, i*i)
In [5]:
f = my_range(3)
In [6]:
f()
In [7]:
next(f)
Out[7]:
In [8]:
next(f)
Out[8]:
In [9]:
next(f)
Out[9]:
In [10]:
next(f)
In [11]:
class my_range():
def __init__(self, n):
self.n = n
self.i = 0
def __iter__(self):
return self
def __next__(self):
i = self.i
if i < self.n:
self.i += 1
return i
else:
raise StopIteration
In [12]:
for i in my_range(3):
print(i, i*i)
In [13]:
f = my_range(3)
In [14]:
f()
In [15]:
next(f)
Out[15]:
In [16]:
next(f)
Out[16]:
In [17]:
next(f)
Out[17]:
In [18]:
next(f)
In [19]:
f = iter(my_range(3))
In [20]:
f()
In [21]:
next(f)
Out[21]:
In [22]:
next(f)
Out[22]:
In [23]:
next(f)
Out[23]:
In [24]:
next(f)
In [25]:
def my_range(n):
i = 0
def gimme():
if i < n:
i += 1
return i - 1
else:
raise StopIteration
return gimme
In [26]:
f = my_range(3)
In [27]:
f()
In [28]:
def my_range(n):
i = 0
def gimme():
nonlocal i
if i < n:
i += 1
return i - 1
else:
raise StopIteration
return gimme
In [29]:
for i in my_range(3):
print(i, i*i)
In [30]:
f = my_range(3)
In [31]:
f()
Out[31]:
In [32]:
f()
Out[32]:
In [33]:
f()
Out[33]:
In [34]:
f()
In [35]:
def my_range(n):
def gimme(i=0):
if i < n:
i += 1
return i - 1
else:
raise StopIteration
return gimme
In [36]:
f = my_range(3)
In [37]:
f()
Out[37]:
In [38]:
f()
Out[38]:
In [39]:
def my_range(n):
i = 0
def gimme(i=i):
if i < n:
i += 1
return i - 1
else:
raise StopIteration
return gimme
In [40]:
f = my_range(3)
In [41]:
f()
Out[41]:
In [42]:
f()
Out[42]:
In [43]:
def my_range(n):
x = [0]
def gimme():
if x[0] < n:
x[0] += 1
return x[0] - 1
else:
raise StopIteration
return gimme
In [44]:
f = my_range(3)
In [45]:
f()
Out[45]:
In [46]:
f()
Out[46]:
In [47]:
f()
Out[47]:
In [48]:
f()
In [49]:
def my_range(n):
i = 0
while i < n:
yield i
i += 1
In [50]:
f = my_range(3)
In [51]:
f()
In [52]:
next(f)
Out[52]:
In [53]:
next(f)
Out[53]:
In [54]:
next(f)
Out[54]:
In [55]:
next(f)