Python Practice › If-Else Programs › Program 8
Check if a number is in the Fibonacci series
Write a Python program to check whether a given number is part of the Fibonacci series (1, 1, 2, 3, 5, 8, 13, …).
Input
8, 10
Output
8 is a Fibonacci number 10 is not a Fibonacci number
Approach
- Generate Fibonacci numbers until they reach or pass the given number.
- If one of them equals the number, it is in the series.
Solution
def is_fibonacci(n): a, b = 0, 1 while a < n: a, b = b, a + b return a == n for n in [8, 10]: print(n, "is a Fibonacci number" if is_fibonacci(n) else "is not a Fibonacci number")Output
8 is a Fibonacci number 10 is not a Fibonacci number
Line by line
Lines 3-4
Keep stepping through the series while the current value is smaller than n.
Line 5
When the loop stops, a is either equal to n (found) or the first value past it (not found).
Learn the concept
New to this topic? Read the lesson, then come back.