Google News
logo
Python Program for Fibonacci numbers
Here's a Python program to generate Fibonacci numbers up to a specified limit :
Program :
def fibonacci(limit):
    a, b = 0, 1
    while a < limit:
        yield a
        a, b = b, a + b

# Example usage
for num in fibonacci(100):
    print(num)
Output :
0
1
1
2
3
5
8
13
21
34
55
89
This program defines a generator function `fibonacci` which yields Fibonacci numbers up to the specified `limit`.

It starts with two variables `a` and `b` initialized to 0 and 1 respectively, and then uses a while loop to generate the next Fibonacci number `a` by adding the current `a` and `b` values, and then swapping the variables `a` and `b`. The loop continues until the `a` value exceeds the specified `limit`.

Finally, the program demonstrates the usage of the `fibonacci` function by iterating over the generated Fibonacci numbers up to 100 and printing them out.