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
# define a list
my_list = [4, 7, 0, 3]
# get an iterator using iter()
my_iter = iter(my_list)
# iterate through it using next()
# Output: 4
print(next(my_iter))
# Output: 7
print(next(my_iter))
# next(obj) is same as obj.__next__()
# Output: 0
print(my_iter.__next__())
# Output: 3
print(my_iter.__next__())
# This will raise error, no items left
next(my_iter)
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? : "))))