hi John
it's simple,
let's make a little modification for the scipt:
def fib(x):
    if x==0 or x==1: return 1
    else: return fib(x-1) + fib(x-2)

for i in range(10):
    print 'fib(%s): ' % i, fib(i)

result:
fib(0):  1
fib(1):  1
fib(2):  2
fib(3):  3
fib(4):  5
fib(5):  8
fib(6):  13
fib(7):  21
fib(8):  34
fib(9):  55

you see, when we put 0 or 1 into fib, we definitely get 1 individually,  if
we put 2 into fib(), inside script we get two fib() result plus 1 + 1.  If
we put 9 into fib(), we get plus of two results of fib(7) and fib(8), that
is 21 + 34, so we get 55.
hope it can give you a little help.

On Thu, Aug 25, 2011 at 12:46 AM, John Gordon <gor...@panix.com> wrote:

> In <f99a156b-56b4-41f4-9599-0dcc31a47...@v9g2000pri.googlegroups.com>
> kangshu...@hotmail.com writes:
>
> > Hi everyone
>
> > I just study python for a few time.
> > Now I have a problem and I holp someone can help me.
> > There is a piece of code:
>
> > def fib(x):
> >     if x==0 or x==1: return 1
> >     else: return fib(x-1) + fib(x-2)
>
> > Could you explain how it works?
> > Thanks for you help.
>
> > Vince
>
> When a function calls itself, as fib() does, it's called recursion.
>
>  http://en.wikipedia.org/wiki/Recursion_(computer_science)
>
> Basically the fib() method keeps calling itself with smaller and smaller
> arguments until it gets 1 or 0.
>
> --
> John Gordon                   A is for Amy, who fell down the stairs
> gor...@panix.com              B is for Basil, assaulted by bears
>                                -- Edward Gorey, "The Gashlycrumb Tinies"
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to