Tuesday, 11 May 2021

Iterator : next channel calling on a remote control

 #iterator will repeat something.

#going through a data list set one by one is called iterating through a loop. here is the code:

a = ["hi", "how", "are", "you", "boss"]
for i in a:
print(i)
#output
hi
how
are
you
boss 
#here is how to actually iterate in a program using __iter__ to make a remote control that calls next channel.
class RemoteControl():
def __init__(self):
self.channels = ["HBO","cnn","abc","espn"] #listing the channels to iterate through
self.index = -1 #index indicates the current channel. here, "-1 means TV off"

def __iter__(self): #calling the iteration method
return self

def __next__(self): #calling the next method to iterate through the self.channels list
self.index += 1 #everytime add 1 to go to the next channel
if self.index == len(self.channels): #if self.index is the last channel
raise StopIteration #then raise StopIteration method.

return self.channels[self.index] #or else, return the channel. self.index will take value from next method.

r = RemoteControl()
itr=iter(r)
print(next(itr))
print(next(itr))
print(next(itr))
print(next(itr))
print(next(itr))

No comments:

Post a Comment