π Day 31/150 – Fibonacci Series in Python
The Fibonacci series is a sequence where each number is the sum of the previous two numbers.
Example: 0, 1, 1, 2, 3, 5, 8, 13...
Let’s explore different ways to print Fibonacci series in Python π
πΉ Method 1 – Using for Loop
n = 10 a, b = 0, 1 for i in range(n): print(a, end=" ") a, b = b, a + b
✅ Most common and efficient method.
πΉ Method 2 – Taking User Input
n = int(input("Enter number of terms: ")) a, b = 0, 1 for i in range(n): print(a, end=" ") a, b = b, a + b
✅ Useful for dynamic programs.
πΉ Method 3 – Using while Loop
n = 10 a, b = 0, 1 count = 0 while count < n: print(a, end=" ") a, b = b, a + b count += 1
✅ Great for loop practice.
πΉ Method 4 – Using Recursion
def fib(n): if n <= 1: return n return fib(n - 1) + fib(n - 2) for i in range(10): print(fib(i), end=" ")
✅ Best for learning recursion concepts
π― Best Method?
✔ for loop → fastest and simple
✔ while loop → beginner friendly
✔ recursion → concept learning


0 Comments:
Post a Comment