Bird
0
0

What will be the output of this code?

medium📝 Predict Output Q13 of 15
Python - Magic Methods and Operator Overloading
What will be the output of this code?
class Count:
    def __init__(self, limit):
        self.limit = limit
        self.num = 0
    def __iter__(self):
        return self
    def __next__(self):
        if self.num < self.limit:
            self.num += 1
            return self.num
        else:
            raise StopIteration

for i in Count(3):
    print(i, end=' ')
AError: StopIteration not handled
B0 1 2
C1 2 3 4
D1 2 3
Step-by-Step Solution
Solution:
  1. Step 1: Understand the iterator behavior

    The Count class starts num at 0 and returns num+1 until it reaches limit 3.
  2. Step 2: Trace the loop output

    Loop prints 1, 2, 3 then raises StopIteration to end loop.
  3. Final Answer:

    1 2 3 -> Option D
  4. Quick Check:

    Count(3) yields 1 to 3 [OK]
Quick Trick: StopIteration ends loop; count from 1 to limit [OK]
Common Mistakes:
  • Starting count from 0 instead of 1
  • Expecting 4 as output
  • Thinking StopIteration causes error

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes