Print nth Fibonacci Number using Python

It’s always complicated when we try to solve difficult questions. However, stepping up with solving easy problems makes perfect sense. But if you’re solving extremely easy questions, then it’s going to take a lot of time to increase your difficulty level. Pattern creating questions are easy but not too easy, so starting with them is a good idea. Therefore today we’re going to print the nth Fibonacci number using python.

Practising these types of questions also helps to get an upper edge in Competitive Programming. So open up your IDE and let’s get started real quick. Once you understand the logic practice this program on your own to make your brain work in a problem-solving way. This is a somewhat easy question so you might not get asked in an interview. But make sure to practice it on your own after reading this article.

 

What’s The Approach?

 

  • We’re going to use a recursive approach for printing the Fibonacci series. As we know the Fibonacci Series starts with 0 1 and the next numbers in this series are the addition of the last two numbers.

 

  • We will consider n the number of Fibonacci we want to print. We will write a function Fibonacci(n) that will return Fibonacci number n. It will call itself recursively until we reach our input n.

 

  • If the input is less than 0 then we will Print Incorrect Input whereas if it’s 0 then we will print 0.

 

  • And If the input is 1,2 we will print 1.

 

Also Read: Check If Two Strings Are Anagram in Python

 

Python Program To Print nth Fibonacci Number

 

Input: 9

Output: 34

 

# Function for nth Fibonacci number
def Fibonacci(n):

    # Check if input is less than 0 then it will
    # print incorrect input
    if n < 0:
        print("Incorrect input")

    # Check if n is 0
    # then it will return 0
    elif n == 0:
        return 0

    # Check if n is 1,2
    # it will return 1
    elif n == 1 or n == 2:
        return 1

    else:
        return Fibonacci(n-1) + Fibonacci(n-2)

# Driver Program
print(Fibonacci(9))


 

Ethix

I'm a coding geek interested in cyberspace who loves to write and read

Leave a Reply

Your email address will not be published. Required fields are marked *