Recursive function defined within function => NameError

Michael Ströder michael.stroeder at inka.de
Thu Feb 17 11:32:49 CET 2000


HI!

I have a problem with a locally-defined recursive function within a
function. Example:

---------------
def func1():

  def fak(n):
    if n>1:
      return n*fak(n-1)
    else:
      return n

  print fak(6)

func1()
---------------

But this code snippet does not work. It produces the traceback:

Traceback (innermost last):
  File "test/rec-func.py", line 15, in ?
    func1()
  File "test/rec-func.py", line 9, in func1
    print fak(6)
  File "test/rec-func.py", line 5, in fak
    return n*fak(n-1)
NameError: fak

Can anybody clarify the issue here? I looked in the Language
Reference and found the hint

---------------
Programmer's note: a ``def'' form executed inside a function
definition defines a local function that can be returned or passed
around. Because of Python's two-scope philosophy, a local function
defined in this way does not have access to the local variables of
the function that contains its definition;
---------------

I applied the standard trick showed there to my example and the
following code works:

---------------
def func1():

  def fak(n,fak):
    if n>1:
      return n*fak(n-1,fak)
    else:
      return n

  print fak(6,fak)

func1()
---------------

Any better solution?

Ciao, Michael.



More information about the Python-list mailing list