Fibonacci Sequence In Python

In my free time, I decided to do some programming. As part of my “programming spree”, I decided to see if I could generate a Fibonacci sequence in Python. And yes I could! I thought that it was amazing and I wanted to share it with you guys. This post will be a very short one, but I hope that this post can show you how simple yet powerful Python can be. Before you continue reading, do follow me and subscribe to my newsletter!

#parameter "no" describes how long you want your sequence to be
def fibonacci(no):
    nicelist = [1, 1]
    first = 1
    second = 1
    third = 0
    if no <= 0:
        return "Nonsense!"
    elif no == 1:
        return [1]
    elif no == 2:
        return [1, 1]
    elif no > 2:
        for i in range(no-2):
            third = first + second
            nicelist.append(third)
            first = second
            second = third
        
    return nicelist 

#will print [1,1,2,3,5,8,13] !!!
print(fibonacci(7))

Published by

bestofwrite

I love to review all things music, books, food and tech!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s