Python - 作为条件的模运算 [英] Python - Modulo Operation as a Conditional

查看:36
本文介绍了Python - 作为条件的模运算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 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.

这篇关于Python - 作为条件的模运算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆