DEV Community

Cover image for Fibonacci Sequence Function
Scott Gordon
Scott Gordon

Posted on

4 1

Fibonacci Sequence Function

# fibonacci_sequence.py
#   This program computes the nth Fibonacci number where n is a value input
#   by the user using a function.
# by: Scott Gordon

def main():
    print("***** Welcome to the Fibonacci Sequencer *****")

    nterms = int(
        input("Enter a number to represent the number of passes through the"
              "Fibonacci Sequence you want: "))

    def fibonacci_sequence(nterms):

        counter = 0
        first = 0
        second = 1
        temp = 0

        while counter <= nterms:
            print(first)
            temp = first + second
            first = second
            second = temp
            counter += 1

    fibonacci_sequence(nterms)


main()

Enter fullscreen mode Exit fullscreen mode

Photo by Ludde Lorentz on Unsplash

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (5)

Collapse
 
mccurcio profile image
Matt Curcio

Yes, but can you do it with recursion? hehe

Collapse
 
sagordondev profile image
Scott Gordon
Comment hidden by post author
Collapse
 
ashish_918 profile image
Ashish Pandey

Yes We can do the same with recursion as well.

Code snippet:

def fibonacci_sequence(nterms):

  # Base case
    if nterms == 1:
       return 1
   if nterms == 0:
      return 0

   # recursive call
    return fibonacci_sequence(nterms-1) + fibonacci_sequence(nterms-2)
Enter fullscreen mode Exit fullscreen mode

We can do memomization here as well because here we are doing many rework as well

Collapse
 
joaomcteixeira profile image
João M.C. Teixeira

Interesting. have a look also here, we were discussing Fibonacci without recursion also

dev.to/joaomcteixeira/fibonacci-wi...

Collapse
 
sagordondev profile image
Scott Gordon

Awesome thanks!

Some comments have been hidden by the post's author - find out more

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay