2014-12-19 42 views
-5
def a(): 
    #function 
    if "b" in c: 
     a() 
    else: 
     #proceed 

我可以这样做吗?一个函数可以调用它自己吗?

+6

当你尝试时发生了什么? – 2014-12-19 10:04:34

+4

这是[递归](https://en.wikipedia.org/wiki/Recursion)这是可能的。 – 2014-12-19 10:04:43

+1

是的,你可以。附加信息:Python中没有私有函数。你要求的是递归。 – 2014-12-19 10:04:53

回答

-5
的原因,你可以

,就是递归函数,例如(删除一个目录,包括子目录和文件):

def removeDir(dirPath): 
    if not os.path.isdir(dirPath): 
     return 
    files = os.listdir(dirPath) 
    try: 
     for file in files: 
      filePath = os.path.join(dirPath, file) 
      if os.path.isfile(filePath): 
       os.remove(filePath) 
      elif os.path.isdir(filePath): 
       removeDir(filePath) 
     os.rmdir(dirPath) 
    except Exception, e: 
     print e 
+5

对于不了解递归的人来说,这将很难理解。也许你应该举一个更简单的例子。 – 2014-12-19 10:12:09

+0

但是我真的认为这已经是一个非常简单的例子了@ VincentBeltman – NeoWu 2014-12-19 10:24:31

+1

我很抱歉,但并没有说明。看看其他答案。它们简单易懂,不需要关于其他库的知识。 (在你的情况下) – 2014-12-19 10:29:42

1

是的,可以。它被称为递归函数。例如考虑下面的程序。

def a(num): 
    if num % 2 == 0: 
     print(num) 
    else: 
     num+= 1 
     a(num) 

a(num)函数需要一个整数。如果它可以被二整除,则打印该值,否则递增变量num并用新输入调用它自己。

>>> a(3) 
4 
>>> a(5) 
6 
>>> a(6) 
6 
2

是的,你可以做到。这将是一个递归函数。举例:

def pow(x, n): 
    if n == 0: #this if makes the function stop calling itself 
     return 1 
    else: 
     return x * pow(x, n-1) 

print(pow(2, 3)) 
>>> 8 

递归是编程或编码问题的一种方式,其中函数在其主体中调用一次或多次。通常,它返回此函数调用的返回值。如果函数定义满足递归条件,我们称这个函数为递归函数。

相关问题