I've been asked to write a program that computes the nth Fibonacci number where n is a value input by the user. For example, if n = 6, then the result is 8.
This is what I have so far:

def main():
print "This program will compute nth Fibonacci"
print "number where n is a value input by the user."

x = input("Enter the nth Fibonacci number: ")
s = 1

for i in range(x):
s = s + x

s = s + 1

print "The result is:", s

main()

I believe I'm missing a variable and I can't figure how to get the previous number to add to the next number.

Preliminary tip: encase your code in (code="Python) and (/code) tags (no spaces on the first tag) so that it'll look pretty.

This is a classic case of recursion:

fib(n) = fib(n-1) + fib(n-2)

The best way to compute it is therefore recursively:

>>> def fib(n):
    if n <= 0:
        return 0
    elif n == 1:
        return 1
    else:
        return fib(n-1) + fib(n-2)

This isn't terribly efficient, and perhaps you were supposed to do it with a loop?

Jeff

commented: helpful advice +6

Try looking in the code snippet section of Daniweb to get an idea. There is one in there.

If you want to access or print all the numbers, append them to a list
test_list = [1, 2] ## Fibs can be started with any 2 numbers
test_list.append( test_list[-1]+test_list[-2] )
print test_list

For Python code on Daniweb:
Please use the [code=python] and [/code] tag pair to enclose your python code.

The cool and simplest program to get fibonacci series is

n=input('enter the value of n')
a=1
b=2
i=0
print '1'
print '2'
for i in range (0,n-2):
    c=a+b
    print c
    a=b
    b=c

compiled by__ Ranjith127 & Varun100

This is what I would do:

# Filename: fib.py
#!usr/bin/pyton
a = int(input('Enter length: '))
x = 0
y = 1
for i in range(a):
    print(x)
    print(y)
    x = x + y
    y = x + y

This is in python 3.1.3

This is very old thread, if you have questions or want critique of your code, start your own fresh thread. Also the OP of this thread wanted to produce single value for nth fibonacci number. That can be made for example like this:

def fib(n):
    prev = [0, 1]
    while n>1:
        prev = prev[-1], sum(prev)
        n -= 1
    return prev[n]
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.