In this tutorial, we are going to print Fibonacci numbers until a given number by using a while loop in Python.
This program generates all the Fibonacci numbers up to a given number n using a while loop.
Simple Code:
n = int(input("Enter a number: "))
a = 0
b = 1
while a <= n:
print(a)
a = b
b = a + b
Output:
Enter a number: 57
0
1
2
4
8
16
32
Code with Comments:
# Here we take Input from user
n = int(input("Enter a number: "))
# Initialize variables
a = 0
b = 1
# Loop until a is less than or equal to n
while a <= n:
# Print the current Fibonacci number
print(a)
# Update a and b to generate the next Fibonacci number
a = b
b = a + b
Explanation:
We start by getting the input from the user by using input function, which is the upper limit n.
Then, we initialize two variables a and b to 0 and 1, respectively.
These variables will keep track of the current and next Fibonacci numbers in the sequence.
We use a while loop to repeatedly check whether a is less than or equal to n.
If it is, we print the current Fibonacci number using the variable a, and then update the variables a and b to generate the next Fibonacci number in the sequence.
The update is done using the expression a = b and b = a + b which first sets a to b (i.e., the next Fibonacci number) and then sets b to a + b (i.e., the sum of the current and next Fibonacci numbers).
This process continues until the current Fibonacci number a is greater than n, at which point the
Discover more from Python Mania
Subscribe to get the latest posts sent to your email.