Python - 作为条件的模运算

2022-01-21 00:00:00 python conditional

问题描述

我在 lambda 函数测试素数中看到了模运算符的这种用法.如果据我所知这不是一个实际的布尔语句,有人可以解释为什么只要 i 大于 x 就会执行以下语句.如果分子大于分母,无论它们是否为因数,它也适用于除法.

I saw such a use of the modulo operator in a lambda function testing for primality. Can someone explain why the following statement will execute as long as i is greater than x if this isn't to my knowledge an actual boolean statement. It works with division as well if the numerator is greater than the denominator regardless if they are factors or not.

if x % i:
    # Execute random foolishness

注意:我只在 Python 和 Java 中尝试过,所以如果这适用于另一种语言,我深表歉意,因为它可能不是特定于语言的问题.

NOTE: I have only tried this in Python and Java so if this works in another language I apologize as it is probably not a language specific question.


解决方案

Python 将非零值视为 True,因此 if x % i:if x % i 相同!= 0:.这只是测试 x 是否可以被 i 整除的快速方法.

Python treats non-zero values as True, so if x % i: is the same as if x % i != 0:. It's just a quick way to test if x is evenly divisible by i.

相关文章