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
Explanation
Here’s how this program works:
- It defines a function called
nth_fibonacci
that takes an argumentn
, representing the Nth term to find. - 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 wheren
is 1 or 2, returning the respective Fibonacci values of 0 and 1. - If
n
is greater than 2, it uses a loop to calculate the Nth Fibonacci term iteratively. It initializesa
andb
to 0 and 1, respectively, and then uses a loop to calculate the next Fibonacci terms until the desired Nth term is reached. - The program takes user input to specify the value of
N
(the term number) for which the Nth Fibonacci term is to be found. - It calls the
nth_fibonacci
function with the user-provided value ofN
. - Finally, it prints the result, which is the Nth Fibonacci term.