Newbie errors :-( Need help

Simon Brunning simon at brunningonline.net
Thu Mar 2 06:19:20 EST 2006


On 3/2/06, - C Saha - <p4sync at yahoo.com> wrote:
> I am getting the result but along with this error, any idea what could be
> the reason?
>
> fibo.fib(1000)
>  1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987Traceback (most recent call
> last):
>   File "<interactive input>", line 1, in ?
>   File "fibo.py", line 8, in fib
>     return result
> NameError: global name 'result' is not defined
>
> Code is given below
> # Fibonacci numbers module
> def fib(n): # write Fibonacci series up to n
>     a, b = 0, 1
>     while b < n:
>         print b,
>         a, b = b, a+b
>     return result

You are returning something called 'result', but you never create
anything with that name.

Since in your function you are printing your results, you should be
able to just drop that line and it'll work just fine.

If OTOH you want your function to return something that can be used
elsewhere, you might try something like (untested):

def fib(n):
    a, b = 0, 1
    result = list()
    while b < n:
        result.append(b)
        a, b = b, a+b
    return result

(You might also do this with a generator - in fact that's not a bad
idea - but generators are an advanced subject, so I'd steer clear for
the moment)

--
Cheers,
Simon B,
simon at brunningonline.net,
http://www.brunningonline.net/simon/blog/



More information about the Python-list mailing list