Q:

Fibonacci sequence in python giving out incorrect result instead of the right one

I am trying to implement the Fibonacci sequence in python 
I am getting the wrong result instead of correct one. The correct one shows     
class FibonacciIterator:
    def __init__(self, max):
        self.max = max

    def __iter__(self):
        self.a = 1
        self.b = 1
        return self

    def __next__(self):
        fib = self.a
        if fib > self.max:
            raise StopIteration
        self.a, self.b = self.b, self.a + self.b
        return fib

fib_ = FibonacciIterator(2)
for term in fib_:
    print(term,end=" ")

Output:
Expected: 1 1
Got: 1 1 2

fib_nums = FibonacciIterator(5)
for term in fib_nums:
    print(term,end=" ")

Output:
Expected: 1 1 2 3 5
Got : 1 1 2 3 5

A:

Your condition to stop the iteration is wrong. You need to set a self.counter to zero in the __init__ method, then in the __next__ method increment this counter and in the condition compare it with max. The second case you got right by coincidence because the fifth element is five. 

