The Fibonacci Sequence in Python

The Fibonacci Sequence. For those that don’t know what it is, it’s a sequence of numbers where you start with the number 1, duplicate it, then add the 2 previous numbers together to make the third. for example: 1+1=2, so the first 3 digits of the sequence are 1, 1, 2. There are a lot of references to this sequence in mathematics. From the “Golden Ratio” to fractals, you could easily fall down this wormhole. My favorite example is from TOOL, in the song “Lateralus”. I still find it absolutely amazing how math came into the making of this song, so here’s the link if you want to see it in action: https://www.youtube.com/watch?v=lsQDSw5AAUU

Mathematically, the sequence is F(n)=F(n-1)+F(n-2).

So, back to what I was doing with Python. I decided to use this sequence as a learning tool for Python. It incorporates the range() function to count steps requested by the user via the input() function at line 1.

end = int(input("How far do we go? "))
fibNumber=0
firstStep=0
secondStep=0
thirdStep=0
total = 0

for x in range(end):
    if (fibNumber == 0):
        print("1", end=", ")
        firstStep = 1
    elif(x != (end - 1)):
        print(fibNumber, end=", ")
    else:
        print(fibNumber)
    thirdStep = secondStep 
    secondStep = firstStep 
    firstStep = secondStep + thirdStep
    fibNumber = firstStep
    total+=int(fibNumber)
    
total=(total+1)-fibNumber
print("The total is:", total, end=".")

Since this is my first iteration of the Fibonacci Sequence in Python, I’m sure as I study it more, I will find better, faster ways to produce the expected outcome, but much like the sequence itself… one step at a time.

EDIT: Well, it didn’t take much time. Looking at how other programmers have coded the same sequence, I’ve found better ways to do it.

# Program to display the Fibonacci sequence up to n-th term
nterms = int(input("How far do we go? "))
n1, n2 = 0, 1 # first two terms
count = 0
total = 0
nth = 0

if nterms <= 0: # check if the number of terms is valid
   print("Please enter a positive integer")
elif nterms == 1:
   print("Fibonacci sequence upto",nterms,":")
   print(n1)
else:
   print("Fibonacci sequence:")
   nterms+=1
   while count < nterms:
        if n1 != 0:
            if (count+1) == nterms:
                print(n1, end=" ")
            else:
                print(n1, end=", ")
        total += n1
        nth = n1 + n2
        # update values
        n1 = n2
        n2 = nth
        count += 1
print("\n Total of the sequence: ", format(total, ","))