为什么不能在条件语句的代码中因式分解 LCM 变量?

Why can you not factor out the LCM variable in the code for conditional statement?

提问人:iTOOK Urzjob 提问时间:12/28/2020 更新时间:12/29/2020 访问量:58

问:

难以理解因式分解为 0 的布尔表达式。

x,y=24,36

LCM=1

counting=True

while counting:
    if (LCM%x and LCM%y) == 0:
        print('The LCM is {}'.format(LCM))
        break
    
    LCM+=1

LCM 计算结果为 24,这是错误的

但此代码给出了正确的 LCM:

x,y=24,36

LCM=1

counting=True

while counting:
    if LCM%x==0 and LCM%y == 0:
        print('The LCM is {}'.format(LCM))
        break
    
    LCM+=1

LCM 是 72,这是正确的

现在为什么不能将 0 分解出来?通常,如果我键入类似 2 和 3 == 0 的内容,表达式的计算结果为 false,但在上面的示例中,语法不应该类似。所以我感到困惑。

python 条件语句 逻辑

评论


答:

1赞 Ananth 12/28/2020 #1

因为在这里,它像二进制操作一样发生,而不是作为逻辑检查语句

(0 和 1) = 0 当 LCM = 24 时

if (LCM%x and LCM%y) == 0:

发生这种情况是因为这里的值是 0 和 1(Python 误认为它是二进制操作,但你想要其他东西)。

如果它像 (24 和 36),那么它将返回 2 的最大值!因此,当您为 Python/任何语言提供条件时要小心!

但这里是值检查,就像 LCM 可以被 x 整除一样

if LCM%x==0 and LCM%y == 0:

是 24%24 == 0?是 36%24 ==0 ?

PS:使用默认的Python IDLE,在这么简单的操作中会让你更清晰的视野!enter image description here

评论

0赞 iTOOK Urzjob 12/30/2020
谢谢,它充分澄清了。
1赞 Z4-tier 12/29/2020 #2

在 python 中,计算结果为 .所以计算到当条件为 时。什么时候发生?每当值 or 为零时。0 == FalseTrue(LCM%x and LCM%y) == 0True(LCM%x and LCM%y)FalseLCM%xLCM%y

在第二个示例中,只有当 both 和 都为零时,才计算结果为 。LCM%x==0 and LCM%y == 0TrueLCM%xLCM%y

评论

0赞 iTOOK Urzjob 12/30/2020
一个简明扼要的答案,表达了这一点。