Python Program To Print Nth Fibonacci Series Term

By | October 31, 2023
Python Program To Print Nth Fibonacci Series Term – You can write a Python program to print the Nth Fibonacci term using a simple iterative approach. Here’s an example:
Source Code
def nth_fibonacci(n):
    if n <= 0:
        return "N should be a positive integer."
    elif n == 1:
        return 0
    elif n == 2:
        return 1
    else:
        a, b = 0, 1
        for _ in range(3, n + 1):
            a, b = b, a + b
        return b

n = int(input("Enter the value of N to find the Nth Fibonacci term: "))

result = nth_fibonacci(n)
print(f"The {n}th Fibonacci term is: {result}")

Output

Enter the value of N to find the Nth Fibonacci term: 5
The 5th Fibonacci term is: 3

Python program to print nth Fibonacci term

Explanation

Here’s how this program works:

  1. It defines a function called nth_fibonacci that takes an argument n, representing the Nth term to find.
  2. It checks if n is less than or equal to 0 and returns an error message in such cases. It also handles the special cases where n is 1 or 2, returning the respective Fibonacci values of 0 and 1.
  3. If n is greater than 2, it uses a loop to calculate the Nth Fibonacci term iteratively. It initializes a and b to 0 and 1, respectively, and then uses a loop to calculate the next Fibonacci terms until the desired Nth term is reached.
  4. The program takes user input to specify the value of N (the term number) for which the Nth Fibonacci term is to be found.
  5. It calls the nth_fibonacci function with the user-provided value of N.
  6. Finally, it prints the result, which is the Nth Fibonacci term.

Loading

Leave a Reply

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