Fibonacci Sequence Function (Python)

The Fibonacci sequence is the series of numbers where each number is the sum of the two preceding numbers before it. For example, the terms of the sequence is 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610… To get these values you need to add 0+0 to get the first term then 0+1=1 to get the second, then 0+1=1 to get the third term, then 1+1=2 then 2+1=3 then 3+2=5 infinitley in that order to get the next following terms. This code is an equation in which you can get these terms without having to perform the necessary calculations. An input leads to an Output. In this case, term input number will give you a value of the fibonacci sequence corresponding to the term number you inputted earlier.



def fibonacci(n):
    # Handle the base cases. These are also terms that have to be followed by the code.
    if n <= 0:
        # establishing that the variable n cannot equal or be less than 0
        return "Input should be a positive integer."
    
    elif n == 1:
        return 0
    #if n=1 the return is 0... these lines are
    #used becasue that is the first fibbonacci number
    elif n == 2:
        return 1
    #this is the second fibbonacci number
    
    # Start with the first two Fibonacci numbers
    fib_1, fib_2 = 0, 1
    
    # Use an iterative approach to find the nth Fibonacci number. This is the function that models the Fibonacci sequence.
    for i in range(3, n+1):
        fib_next = fib_1 + fib_2
        fib_1, fib_2 = fib_2, fib_next
    #the loop starts at 3 and runs until n variable plus 1
    #fib next is the  sum of previous 2 fibonacci sequnces
    # 
    return fib_2
#when the loop finishes, fib 2 is the nth fibonacci number 
n = 8
result = fibonacci(n)

#you want to end with an output message so you need to use print
print(f"The {n}th Fibonacci number is: {result}")
The 9th Fibonacci number is: 21