# examples of generators # # Matt Bishop, MHI 289I, Fall 2023 # # first, our version of range myrange = (x for x in range(5)) print("call #1 to range(5) generator, next(myrange): ", next(myrange)) print("call #2 to range(5) generator, next(myrange): ", next(myrange)) print("call #3 to range(5) generator, next(myrange): ", next(myrange)) print("call #4 to range(5) generator, next(myrange): ", next(myrange)) print("call #5 to range(5) generator, next(myrange): ", next(myrange)) try: print("call #6 to range(5) generator, next(myrange): ", next(myrange)) except StopIteration: print("In call #6, we went too far, so got a StopIteration exception") # now we use this to compute the sum of the first 100 numbers print("The sum of the first 100 integers is", sum(x for x in range(101))) # another version of range, as a full function def genmyrange(n): for i in range(n): yield i # and here's how we use it for i in genmyrange(10): print(i) print(genmyrange(10)) # and now our version of range without using range def genmyrange2(n): # start here i = 0 # loop until you put out the last number (n-1 while i < n: # yield here normally returns None # you can use the send() method to have # yield return a different value, and # that value becomes the new value of # the counter value = (yield i) if value is not None: i = value else: i += 1 # and here's how we use it print("-----") for i in genmyrange2(10): print(i)