Fibonacci Iterator
Lesson 11 of 13 in Coddy's Python Iterators course.
Challenge
EasyCreate a FibonacciIterator class that generates Fibonacci numbers up to a specified limit. The class should implement the iterator protocol and have the following methods:
__init__(self, limit): Initialize the iterator with a limit.__iter__(self): Return the iterator object itself.__next__(self): Generate the next Fibonacci number or raise StopIteration when the limit is reached.
After implementing the FibonacciIterator class, create an instance of it using the input value as the limit. Then, iterate through the Fibonacci numbers and print each number on a new line until the StopIteration exception is raised.
The following input will be provided:
- An integer representing the upper limit for the Fibonacci sequence
Try it yourself
# Read input
limit = int(input())
class FibonacciIterator:
def __init__(self, limit):
self.limit = limit
# TODO: Initialize other necessary attributes
def __iter__(self):
# TODO: Implement __iter__ method
def __next__(self):
# TODO: Implement __next__ method
# Create an instance of FibonacciIterator
fib_iterator = FibonacciIterator(limit)
# TODO: Iterate through the Fibonacci numbers and print each number
# Hint: Use a for loop or while loop with try-except to handle StopIteration
# Example of how to print a Fibonacci number:
# print(fib_number)