如何使用正确的“参数”调用函数

时间:2012-02-20 17:28:10

标签: python

我有一个函数,它从另一个函数中获取2个返回的变量,用更多的填充文本写入外部文本文件。

我用来写入文本文件的代码如下所示,但它在运行时使用程序底部的if语句自动调用

def function1()
# Some code

def function2()
# Some code
return startNode
return endNode

def function3(var)
# Some code
return differentVariable

def createFile(startNode, endNode):
    outputFile = open('filename.txt','w')                   # Create and open text file
    start = chr(startNode +65)                              # Converts the int to its respective Char
    end = chr(endNode +65)                                  # Converts the int to its respective Char
    outputFile.write('Route Start Node: ' + start + '\n')   # e.g Route Start Node: B
    outputFile.write('Route end node: ' +  end + '\n')      # e.g Route End Node: F
    outputFile.write('Route: ' + Path + '\n')               # e.g Path: B,A,D,F
    outputFile.write('Total distance: ' + Distance)         # e.g Total Distance: 4
    outputFile.close                                        # Close file


if __name__ == "__main__":
    function1()
    function3(function2())
    createFile( # Don't Know What Goes Here  )

目前我只能通过手动调用并输入createFile(1,5)来运行此功能,其中1是startNode值,5是endNode值

但是如果我要将createFile(startNode, endNode)放在if语句中来调用该函数,它会告诉我NameError: name 'startNode' is not defined然后它显然会给我同样的endNode错误

如何在不必手动输入值的情况下正确调用该函数,因为它们可能会根据程序开头的startNode和endNode值而改变?

3 个答案:

答案 0 :(得分:2)

您不能像在function2的示例中那样返回两个变量。执行将在第一个返回值处退出函数,并且永远不会使其返回到第二个返回值。相反,你需要返回一个元组:

def function2():
    # set the values of startNode and endNode here
    # e.g.
    startNode = 1
    endNode = 5
    return (startNode, endNode)

然后当你打电话给function2时,按照Ade描述的那样做:

if __name__ == "__main__":
    startNode, endNode = function2()
    createFile(startNode, endNode)

答案 1 :(得分:1)

  

但是如果我要将createFile(startNode, endNode)放在if语句中来调用该函数,它会告诉我NameError: name 'startNode' is not defined

显然,因为当时正在考虑的是:

if __name__ == "__main__":
    function1()
    function3(function2())
    createFile(startNode, endNode)

因此,如果您希望最后一次调用成功,则需要在某处定义这些变量。

我猜测之前的那些函数调用用于以某种方式初始化值。您可能会在其中“设置”startNodeendNode一些方法,但这不起作用,因为函数内部的变量通常是本地的。所以你要做的就是从函数中返回值并保存它们:

if __name__ == "__main__":
    startNode = function1()
    endNode = function3(function2())
    createFile(startNode, endNode)

功能应如下所示:

def function1 ():
    # some computations
    return startNode

def function3 (param):
    # more computations
    return endNode

答案 2 :(得分:0)

您应该将startNodeendNode分配给某些值。

如果它们是由前两个函数返回的:

if __name__ == "__main__":
    startNode = function1()
    endNode = function3(function2())
    createFile(startNode, endNode)