【问题标题】:Returning a string from a Python function从 Python 函数返回字符串
【发布时间】:2014-12-07 14:55:15
【问题描述】:
def God():
    set_path()

    find_files(path)

def set_path():
    '''Sets file path to inputted directory'''

    # Should path default to a certain directory if path is invalid?
    # (it does here)
    #path = Path(input("Enter path\n"))
    path = Path(input("Specify a directory:\n")
    print("Path set to", path.cwd())
    return path



def find_files(path):
    '''Stores files in current dir and all subdirs to a list'''

    myFiles = []
    for element in path.iterdir():
        if element.is_dir() == True:
            find_files(element)
        else:
            myFiles.append(element)
    print(myFiles)
    return myFiles

*** God 函数结合了这两个函数,应该返回设置路径的目录和子目录中所有文件的列表,但是我一直收到此错误消息:

Traceback (most recent call last):
  File "<pyshell#11>", line 1, in <module>
    God()
  File "C:/Users/Project1.py", line 8, in God
    return path
NameError: name 'path' is not defined

关于如何返回字符串以供以后在上帝函数和所有后续函数中使用的任何想法?

【问题讨论】:

  • 这还能编译吗?您缺少括号。

标签: python string return


【解决方案1】:

您的问题不在于 set_path 没有返回路径——它正在返回它——而是它的调用者正在丢弃返回值。

要解决此问题,请更改此行:

    set_path()

到这里:

    path = set_path()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-05
    • 1970-01-01
    • 2010-12-14
    • 2014-11-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多