What will be the result of executing the following code?
class I: def __init__(self): self.s = 'abc' self.i = 0 def __iter__(self): return self def __next__(self): if self.i == len(self.s): raise StopIteration v = self.s[self.i] self.i += 1 return v for x in I(): print(x,end='')
- it will print abc
- it will print 0
- it will raise an handled exception
- it will raise an unhandled exception
Explanation: Let’s analyze this code snippet:
- First, a for loop using the x variable iterates through the already defined I() generator.
- The generator class initializes the self.s = ‘abc’ and self.i = 0 variables within the constructor.
- The __next__ method compares if the value in i is equal to the length of s.
- Since it is not, v is assigned the first character of s, which is a, i is incremented by one, v is returned and printed in the console.
- The end=’’ argument in the print function will prevent new lines, so all the outputs will be shown on the same line.
- The iteration continues for the remaining characters in s. The b and c characters are also printed in the console.
- When the condition self.i == len(self.s) becomes true, a StopIteration is raised. This terminates the execution.
More Questions: Python Essentials 2 – Module 3 Test
Please login or Register to submit your answer