Solution Review: Create a Fibonacci Iterator

The solution to the 'Create a Fibonacci Iterator' challenge.

Press + to interact
class Fibonacci:
def __init__(self, n):
self.limit = n
self.count = 1
self.a = 0
self.b = 1
def __iter__(self):
return self
def __next__(self):
if self.count <= self.limit: # Controlled iterations
x = self.a
self.a, self.b = self.b, self.a +self.b # Adding preceding values
self.count += 1
return x
else:
raise StopIteration
fib = Fibonacci(7)
iterator = iter(fib)
for x in iterator:
print(x)

Get hands-on with 1400+ tech skills courses.