xxxxxxxxxx
class Reverse:
"""Iterator for looping over a sequence backwards."""
def __init__(self, data):
self.data = data
self.index = len(data)
def __iter__(self):
return self
def __next__(self):
if self.index == 0:
raise StopIteration
self.index = self.index - 1
return self.data[self.index]
xxxxxxxxxx
class CoinFlips:
def __init__(self, number_of_flips):
self.number_of_flips = number_of_flips # Store the total number of flips
self.counter = 0
def __iter__(self):
return self # Return a reference of the iterator
def __next__(self):
if self.counter < self.number_of_flips:
self.counter += 1
return random.choice(["H", "T"]) # Flip the next coin, return the output
else: # Otherwise, stop execution with StopIteration
raise StopIteration
while True:
try:
next(three_flips) # Pull the next element of three_flips
# Catch a stop iteration exception
except StopIteration:
print("Completed all coin flips!")
break
xxxxxxxxxx
fruits = ["apples", "bananas", "cherries", "pears", "plums"]
fruitIterator = iter(fruits);
print(next(fruitIterator))
print(next(fruitIterator))
print(next(fruitIterator))
xxxxxxxxxx
def iter(times):
it = 1
for i in range(times):
its = it * 2
it = its
return it
while True:
print()
print(iter(int(input("how many iteration? : "))))