Python程序无法返回指定值,控制台打印None问题求助
问题分析与修复方案
问题根源
check_equal函数未传递返回值:这个函数只调用了f(x,y,z),但没有把f的返回结果返回出去,所以调用check_equal时默认返回None。f函数全相等分支无返回语句:当三个值完全相等时,执行完打印逻辑后没有返回对应数值,函数默认返回None。
修复后的代码
def f(v1, v2, v3): if v1 == v2 and v2 == v3: print("Applying f to all three values gives the same result" + str(v1)) return v1 # 添加返回语句 if v1 == v2 and v1 != v3: print("Only applying f to x and y gives the same result") return v1 if v2 == v3 and v2 != v1: print("Only applying f to y and z gives the same result") return v2 if v1 == v3 and v1 != v2: print("Only applying f to x and z gives the same result") return v1 if v1 != v2 and v2 != v3: print("Applying f to x,y,z gives all different results") def check_equal(f, x, y, z): return f(x, y, z) # 添加返回语句,传递f的执行结果 tests = [(42, 1, 42), (1, 1, -5), (5, 4, -1), (5, 5, 5), (0, 0, 1), (-9, 9, 9), (9, 8, 90)] for x, y, z in tests: print(check_equal(f, x, y, z))
修复说明
- 给
check_equal函数加上return f(x,y,z),让它把f的返回值传递出去,这样调用check_equal时就能拿到预期的返回结果。 - 在
f函数的三个值相等分支中添加return v1,确保这种场景下也能返回匹配的数值,而不是默认的None。
内容的提问来源于stack exchange,提问作者patrik maco
相关产品推荐
相关产品推荐

