Python随机测试中throw()函数返回None的问题求助
问题根源
你遇到的问题是递归分支没有返回递归调用的结果。当throw()函数掷出"tails"时,你调用了throw(num)但没有将这个调用的返回值传递回去,导致当前函数执行完这个分支后没有任何return语句,Python函数默认会返回None。
修复代码
修改throw()函数,在递归调用时加上return:
import random tails_in_a_row = 0 def heads_tails(): outcomes = ("heads", "tails") outcome = random.choice(outcomes) return outcome def throw(num): outcome = heads_tails() if outcome == "tails": num += 1 return throw(num) # 这里加上return,把递归结果传递回去 else: return num for i in range(10): outcome = throw(tails_in_a_row) print(outcome)
为什么之前的
print(type(num))显示是整数? 你看到的整数是最底层递归调用里的num值(也就是最后一次掷出"heads"时返回的那个整数),但上层的递归函数没有把这个值返回出来,所以最终回到主调函数时,拿到的是上层函数默认返回的None。
内容的提问来源于stack exchange,提问作者Tomer_TheG
相关产品推荐
相关产品推荐

