def my_generator(): yield 1 yield 2 yield 3 # Using the generator function gen = my_generator() print(next(gen)) # Output: 1 print(next(gen)) # Output: 2 print(next(gen)) # Output: 3
1 2 3
def countdown(n): while n > 0: yield n n -= 1 # Using the generator in a for loop for num in countdown(5): print(num) # Output: 5 4 3 2 1
5 4 3 2 1