Python,生成函数

2024-04-26 11:07:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在为我的代码而挣扎。现在我的老师想让我用这个做一个函数,我真的很努力,但我想不出来。 所以我需要用它做一个函数,然后再向下调用它。有人能帮帮我吗?或者给我一些提示:):)

opengraph = False 

while opengraph is not True:
    if len(sys.argv) == 2:
        name = sys.argv[1]
        g = openmap(name)
        opengraph = True
    else:
        try:
            name = raw_input('Please enter a file: ')
            g = openmap(name)
            opengraph = True
        except:
            print 'Not able to read the file you wrote, try another time.'
origdest = raw_input('Enter origin and destination (quit to exit): ')

Tags: to函数代码nametrueinputrawsys
2条回答

我希望这个链接对本教程有帮助,函数必须定义,然后调用才能执行。在Python中,函数在语法上如下所示。。。你知道吗

def nameOfFunction (parameters):
    code to perform task/tasks...

# Call your function...
nameOfFunction(parameter)

请按此链接转到教程并祝您好运!Link to tutorial

网上有很多关于你如何做到这一点的参考资料。比如这个one,或者这个one,或者这个one。你知道吗

不管怎样。。您需要使用def,给它一个名称和输入参数,如下所示:

def MyFunction(input1, input2):
   # <Rest of the code here>

不要忘记标识,如果希望函数返回某些内容,则需要插入:

return output1, output2, output3

最后。你知道吗

一旦定义了函数,只需在主代码中调用它,并传递正确的输入参数(如果有)。你知道吗

output1, output2, output3 = MyFunction(input1, input2)

相关问题 更多 >