gpt4 book ai didi

python - 'if x % 2 : return True' , 如果数字可以被 2 整除,那不会返回 True 吗?

转载 作者:太空狗 更新时间:2023-10-30 00:23:23 26 4
gpt4 key购买 nike

我不明白 if not x % 2: return True 是如何工作的。这是否意味着如果 x 不能被 2 整除,则返回 True?这就是我在这段代码中看到的。

我将其视为 if not x % 2: return True 将返回与 if a number is divisible by 2, return True 相反的结果。

我只是不明白那部分语法是如何工作的。

def is_even(x):
if not x % 2:
return True
else:
return False

最佳答案

Wouldn't that mean this if x is not divisible by two, return True?

不,因为当 x 不能被 2 整除时,x%2 的结果将是一个非零值,它会被 Python 评估为 True,所以它not 将是 False

阅读更多关于 Truth value testing 的信息在 python 中。

关于python - 'if x % 2 : return True' , 如果数字可以被 2 整除,那不会返回 True 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34385292/

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