Platform

Rohit Deshmukh
0
DSA Fibonacci Tutorial

Fibonacci Numbers Algorithm with Python

The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones, starting from 0 and 1. Here, we will explore how to generate Fibonacci numbers using both loops and recursion in Python.

1. Using a For Loop


prev2 = 0

prev1 = 1

print(prev2)

print(prev1)

for fibo in range(18):

    newFibo = prev1 + prev2

    print(newFibo)

    prev2 = prev1

    prev1 = newFibo

    

Try It Yourself!


2. Using Recursion


def fibonacci(n):

    if n <= 1:

        return n

    else:

        return fibonacci(n-1) + fibonacci(n-2)

print(fibonacci(10))

    

Interactive Test Section

Test Your Knowledge!

What will be the 5th Fibonacci number?





Gamify Your Learning!

Earn points for completing each section successfully. More points unlock new challenges.

Points: 0

Post a Comment

0Comments

Post a Comment (0)