Python,函数输出不符合预期

Python,函数输出不符合预期,python,recursion,directory,Python,Recursion,Directory,我用python编写了一个创建目录的函数。如果已使用原始名称,则该函数会向directoryname添加扩展名,例如_1。 该函数按预期工作并创建文件夹;但是返回值有问题。当我把它打印出来时,我一个也没有得到。这是我的密码。可能不是最干净的:s。这与在函数内部调用自身有关,但我不确定如何修复它 import os ##function to generate a dir with extension if it already exists def createDir(directory,e

我用python编写了一个创建目录的函数。如果已使用原始名称,则该函数会向directoryname添加扩展名,例如_1。 该函数按预期工作并创建文件夹;但是返回值有问题。当我把它打印出来时,我一个也没有得到。这是我的密码。可能不是最干净的:s。这与在函数内部调用自身有关,但我不确定如何修复它

import os


##function to generate a dir with extension if it already exists
def createDir(directory,ext):
  thePath=directory+ext
  if not os.path.exists(thePath):
    os.makedirs(thePath)
    output=thePath + '/'
    print 'I return ' + output #I got "I return /media/usb0/incomplete_noNameYet_2/ (Because incomplete_noNameYet and incomplete_noNameYet_1 already existed)" This is fine!
    return output
  else:
    if ext =='':
      ext='_1'
    else:
      ext= '_' + str(int(ext[1:len(ext)])+1)
    createDir(directory,ext)

def main():
  print createDir('/media/usb0/incomplete_noNameYet','') #I got none.   

if __name__ == '__main__':
  main() 

您忽略了递归调用的返回值;在那里也添加一个
返回

return createDir(directory,ext)

否则,
createDir()
的返回值将被丢弃,父函数调用返回时没有显式的
return
调用,默认为
None
您将忽略递归调用的返回值;在那里也添加一个
返回

return createDir(directory,ext)

否则,
createDir()
的返回值将被丢弃,并且父函数调用返回时没有显式的
return
调用,默认为
None
问题是在else分支上调用createDir,而没有返回值。对createDir的初始调用执行第二个两个递归调用(包括它们的副作用),但随后丢弃返回值并不返回任何值。

问题在于,在else分支上,您正在调用createDir,而不返回值。对createDir的初始调用执行第二个两个递归调用(包括它们的副作用),但随后丢弃返回值并不返回任何值