How can you create a generator in Python?
In the first example, we are going to create a generator that generates even numbers. Here is the code:
In this code, we define a function called even_numbers that takes a number n as input. We then use a for loop to iterate through numbers up to n and check if the number is even using the condition if i % 2 == 0 . If the number is even, we yield it. We then create a generator object even_nums by calling the even_numbers function with an argument of 10. Finally, we loop through the generator object using a for loop and print each even number. In the second example, we are going to create a generator that generates Fibonacci numbers. Here is the code:
In this code, we define a function called fibonacci that takes a number n as input. We initialize two variables a and b to 0 and 1 respectively, which are the first two Fibonacci numbers. We then use a while loop to generate Fibonacci numbers up to n using the yield keyword. We create a generator object fib_nums by calling the fibonacci function with an argument of 10. Finally, we loop through the generator object using a for loop and print each Fibonacci number.
def even_numbers(n): for i in range(n): if i % 2 == 0: yield i # Create a generator object even_nums = even_numbers(10) # Loop through the generator and print each even number for num in even_nums: print(num)
In this code, we define a function called even_numbers that takes a number n as input. We then use a for loop to iterate through numbers up to n and check if the number is even using the condition if i % 2 == 0 . If the number is even, we yield it. We then create a generator object even_nums by calling the even_numbers function with an argument of 10. Finally, we loop through the generator object using a for loop and print each even number. In the second example, we are going to create a generator that generates Fibonacci numbers. Here is the code:
def fibonacci(n): a, b = 0, 1 count = 0 while count < n: yield a a, b = b, a + b count += 1 # Create a generator object fib_nums = fibonacci(10) # Loop through the generator and print each Fibonacci number for num in fib_nums: print(num)
In this code, we define a function called fibonacci that takes a number n as input. We initialize two variables a and b to 0 and 1 respectively, which are the first two Fibonacci numbers. We then use a while loop to generate Fibonacci numbers up to n using the yield keyword. We create a generator object fib_nums by calling the fibonacci function with an argument of 10. Finally, we loop through the generator object using a for loop and print each Fibonacci number.
Comments
Post a Comment