Here's is my generator function code:
def fibo():
n1=0
n2=1
while True:
if n1 == 8:
raise StopIteration
else:
yield n1
n1,n2=n2,n1+n2
seq=fibo()
Here is my code version-1 for generating sequence:
for ele in seq:
print(next(seq))
Output:
1
2
5
RuntimeError: generator raised StopIteration
---------------------------------------------------------------------------
StopIteration Traceback (most recent call last)
<ipython-input-3-c01815b93e23> in fibo()
5 if n1 == 8:
----> 6 raise StopIteration
7 else:
StopIteration:
The above exception was the direct cause of the following exception:
RuntimeError Traceback (most recent call last)
<ipython-input-3-c01815b93e23> in <module>
11 seq=fibo()
12
---> 13 for ele in seq:
14 print(next(seq))
15
RuntimeError: generator raised StopIteration
My expected output for version-1:
0
1
1
2
3
5
Here is my code version-2 for generating sequence:
while True:
try:
print(next(seq))
except StopIteration:
print('This exception is raised in the generator operation defining function. Hence it is handled here.')
break
Output:
0
1
1
2
3
5
RuntimeError: generator raised StopIteration
---------------------------------------------------------------------------
StopIteration Traceback (most recent call last)
<ipython-input-4-6afe26583a33> in fibo()
5 if n1 == 8:
----> 6 raise StopIteration
7 else:
StopIteration:
The above exception was the direct cause of the following exception:
RuntimeError Traceback (most recent call last)
<ipython-input-4-6afe26583a33> in <module>
16 while True:
17 try:
---> 18 print(next(seq))
19 except StopIteration:
20 print('This exception is raised in the generator operation defining function. Hence it is handled here.')
RuntimeError: generator raised StopIteration
My expected output for version-2:
0
1
1
2
3
5
This exception is raised in the generator operation defining function. Hence it is handled here.
In the first version, out is incorrect and exception is happening. In the second, in addition to correct output, same exception as version-1 is happening. Please help me to rectify this.