Fibonacci series up to 50
Write a Python program to print the Fibonacci series between 0 and 50. Each number is the sum of the two before it.
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
Approach
- Start with a = 0 and b = 1.
- Print
a, then move forward witha, b = b, a + buntilapasses 50.
Solution
a, b = 0, 1series = []while a <= 50: series.append(a) a, b = b, a + bprint(series)[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
Line by line
The series starts with 0 and 1.
The loop stops as soon as the next number would be above 50.
Both variables update at once: the new a is the old b, and the new b is the sum of the old pair.
Learn the concept
New to this topic? Read the lesson, then come back.