gpt4 book ai didi

python - python 中的一行 if else 条件

转载 作者:太空狗 更新时间:2023-10-30 01:39:37 27 4
gpt4 key购买 nike

def sum10(a, b):
if sum([a, b]) % 10 == 0: return True; return False

print sum10(7, 3)
print sum10(-13, -17)
print sum10(3, 8)

结果是:

True
True
None

不是我所期望的:

True
True
False

有什么想法吗?

最佳答案

你的代码

def sum10(a, b):
if sum([a, b]) % 10 == 0: return True; return False

相当于

def sum10(a, b):
if sum([a, b]) % 10 == 0:
return True; return False

所以 return False 永远不会被评估。


一些(可能无穷无尽的)替代方案:

    if sum([a, b]) % 10 == 0: 
return True
return False

    return sum([a, b]) % 10 == 0

    return True if sum([a, b]) % 10 == 0 else False

    return False if (a+b) % 10 else True

或(最易读的恕我直言)

    return not (a + b) % 10

关于python - python 中的一行 if else 条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13134743/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com