简体   繁体   中英

Return function not working- new_node value is printing inside but while returning it is not returning it

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)

above function return me newnode that is booting or queued I am getting it on printing but while returning it is returning None

Returning None is the default behaviour when you do not put a return statement at the end of your function. If the function has several ways to end, you have to end each coding path by a return, or put one at the end of it. If your newnode is not empty, you do nothing, so default value None is returned. To be sure, it is safer to put a valid return statement at the end of each code path:

So you forgot extra 'return newnode' at the last line of the function:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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