简体   繁体   English

Python,函数输出不符合预期

[英]Python, function output not as expected

I wrote a function to create a directory in python. 我编写了一个在python中创建目录的函数。 The function adds an extension for example _1 to the directoryname if the original name was already taken. 如果原始名称已被使用,该函数会将扩展名(例如_1)添加到目录名称。 The function works and creates the folder as expected; 该功能可以正常工作并创建文件夹; But there is something wrong with the returnvalue. 但是返回值有问题。 When I print it out I get None. 当我打印出来时,我什么也没有。 Here is my code. 这是我的代码。 Probably not the cleanest :s. 可能不是最干净的:s。 This has something to do with calling itself inside the function, but I'm not sure how to fix it. 这与在函数内部调用自身有关,但是我不确定如何修复它。

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() 

You are ignoring the return value of the recursive call ; 您将忽略递归调用的返回值; add a return there too: 也在那里添加return

return createDir(directory,ext)

otherwise the return value of createDir() is discarded, and the parent function call returns with no explicit return call, defaulting to None . 否则,将放弃createDir()的返回值,并且父函数调用将不带任何明确的return调用而return ,默认为None

The problem is that on the else branch, you are calling createDir and not returning the value. 问题是在else分支上,您正在调用createDir而不返回该值。 The initial call to createDir carries out the second two recursive calls (including their side effects) but then discards the return value and returns None. 最初对createDir的调用执行后两个递归调用(包括它们的副作用),但随后放弃返回值并返回None。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM