为什么我的Python函数不返回任何内容(第一次它会返回true,但递归函数调用本身则不会返回任何内容)

问题描述 投票:0回答:1
def login(log = 1):
    
    con = input(f"{na} are you Ready for the game Yes/NO ")
    if ((con == "Yes")or(con == "yes")or(con == "y")or(con == "Y")):
        print("\nwelcome to The Game") # first time it will return true but recursive function call itself then it will return none 
        return True

    elif(log == 3):
        print("retry after long time")
    else:
        print("Retry again")
        log = log + 1
        login(log)

flag = login()
print(flag)

预期输出:

flag = True

输出:

flag = None

python python-3.x python-2.7 recursion helper
1个回答
0
投票

如此接近,您只是在递归调用中缺少返回语句,因此成功时的返回值使其返回到原始调用,我已在此处展示了这一点。

def login(log=1):
    con = input(f"{na} are you Ready for the game Yes/NO ")
    if ((con == "Yes") or (con == "yes") or (con == "y") or (con == "Y")):
        print("\nwelcome to The Game")  
        return True

    elif (log == 3):
        print("retry after long time")
    else:
        print("Retry again")
        log = log + 1
        return login(log) # this line required the return

na = 'YOURNAME'
flag = login()
print(flag)

如果您有任何疑问,请告诉我。

© www.soinside.com 2019 - 2024. All rights reserved.