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

Viewed 48

Having trouble understanding Boolean expression for factoring out 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 evaluates to 24, which is false

But this code gives the correct 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 is 72, this is correct

Now why can 0 not be factored out? Generally if I type something like 2 and 3 == 0, the expression evaluates to false, but shouldn't syntax work similarly in the example above. So I getting confused.

2 Answers

Because here' it's happening like a binary operation and not as a logical check statement

(0 and 1) = 0 when LCM = 24

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

This is happening because the values are 0 and 1 here(Python mistook it for a binary operation but you wanted something else).

If it is like (24 and 36) then it would return the max of two! So be careful when you give conditions to Python/any language!

But here it is the value check like is LCM divisible by x like

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

is 24%24 == 0? and is 36%24 ==0 ?

PS : Use the default Python IDLE, it will give you a clearer view in such simple operations! enter image description here

In python, 0 == False evaluates to True. So (LCM%x and LCM%y) == 0 evaluates to True when the condition (LCM%x and LCM%y) is False. When does that happen? Whenever either of the values LCM%x or LCM%y is zero.

In your second example, you have LCM%x==0 and LCM%y == 0 which evaluates to True only if both LCM%x and LCM%y are zero.

Related