Now we are going to discuss how to print the Fibonacci series up to a given number using a while loop in Python:
Simple code:
n = 100
a = 0
b = 1
while a <= n:
print(a, end=' ')
a = b
b = a + b
Output:
0 1 2 4 8 16 32 64
Code with comments:
# set the maximum value for the Fibonacci series
n = 100
# initialize the first two numbers in the series
a = 0
b = 1
# loop while the current number in the series is less than or equal to n
while a <= n:
# print the current number in the series
print(a, end=' ')
# update the first two numbers in the series to the next two numbers
a = b
b = a + b
In the above code, we first set the maximum value for the Fibonacci series to n and initialize the first two numbers in the series to 0
and 1
using multiple assignment.
We then use a while loop to print each number in the series up to n.
Inside the loop, we print the current number in the series using the print() function and update the first two numbers in the series to the next two numbers using multiple assignment.
Discover more from Python Mania
Subscribe to get the latest posts sent to your email.