返回函数不起作用 - new_node 值正在内部打印但返回时未返回它

问题描述

def function():
    res = get_nodes(api_server_call,token)
    newnode = ""
    #endTime = ""
    for node in res:
        if (node['state'] == "booting" or node['state'] == "queued"):
            newnode = node['name']
            print("new node is : " + newnode)
            return newnode
    if(newnode == ""):
        function()


new_node = function() >this is main function from where above function is called
print(new_node)

上面的函数返回我正在启动或排队的新节点我正在打印它但在返回时它返回无

解决方法

返回 None 是当您不在函数末尾放置 return 语句时的默认行为。如果函数有多种结束方式,则必须通过返回来结束每个编码路径,或者在其末尾放置一个。如果您的 newnode 不为空,则您什么都不做,因此返回默认值 None 。可以肯定的是,在每个代码路径的末尾放置一个有效的 return 语句更安全:

所以你在函数的最后一行忘记了额外的“return newnode”:

def function():
    res = get_nodes(api_server_call,token)
    newnode = ""
    #endTime = ""
    for node in res:
        if (node['state'] == "booting" or node['state'] == "queued"):
            newnode = node['name']
            print("new node is : " + newnode)
            return newnode

    if(newnode == ""):
        return function()

    return newnode


## main part of the code:
new_node = function() ##>this is main where function is called
print(new_node)