SoFunction
Updated on 2025-03-02

Example code for finding the value of the nth number in a Fibonacci sequence using python

The Fibonacci sequence, also known as the golden segmentation sequence, was introduced by the mathematician Leonardoda Fibonacci, using rabbit breeding as an example, so it is also called the "rabbit sequence", which refers to a sequence: 1, 1, 2, 3, 5, 8, 13, 21, 34, ... In mathematics, the Fibonacci sequence is defined in the following recursive method: F(1)=1, F(2)=1, F(n)=F(n-1)+F(n-2)(n>=2, n∈N*)

Find the value of the nth number in the Fibonacci sequence: 1, 1, 2, 3, 5, 8, 13, 21, 34…

Method 1: Use a for loop

n = int(input('Please enter an integer:'))
n_2 = 0
n_1 = 1
current = 1
for x in range(2, n+1):
  current = n_2 + n_1
  n_2 = n_1
  n_1 = current
print('The %d number is %d'%(n, current))

Method 2: Recursive function

def fab(n):
  if n == 1 or n == 2:
    return 1
  return fab(n-1) + fab(n-2)

print(fab(5))

Method 3: Generator

def fib(n):
  a, b = 0, 1
  for _ in range(n):
    a, b = b, a + b
    yield a
    
for val in fib(20):
  print(val)

Summarize

This is the article about using python to find the value of the nth number in the Fibonacci sequence. For more related contents of the nth number in the python Fibonacci sequence, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!