首页 > 解决方案 > Python返回值必须写两次?

问题描述

def simulate_tournament(teams):

    if len(teams) == 1:
        return teams[0]['team']
    else:
        teams = simulate_round(teams)
        simulate_tournament(teams)
    return teams[0]['team']
 return teams[0]['team']

如果没有 if else 语句之外的最后一行,我的代码将无法运行。但我不明白为什么我需要这个?len(teams) == 1在函数返回团队之前,函数不会迭代吗?

标签: python

解决方案


由于您的 else 块没有return语句或任何对象来保存数据,因此对于递归调用,它正在调用并没有返回,因此您没有得到任何结果

def simulate_tournament(teams):
    if len(teams) == 1:
        result= teams[0]['team']
    else:
        teams = simulate_round(teams)
        result = simulate_tournament(teams)
    return result

推荐阅读