Difference between logical "and" and bit wise &

43 Views Asked by At

I was writing a piece of code for a practice problem where I was trying the display the highest odd number. I kept running into a problem where when I was linking two statements together with a & symbol it was coming as true even though when evaluated separately the second statement was false. when I changed from & to and instead it then started to evaluate correctly. the code I wrote is below.

x = 21
y = 57
z = 7

a = x
if x > y:
    a = y
    if y > z:
        a = z
elif x > z:
    a = z


if x%2 != 0:
    a = x
if y%2 != 0 & (y > a):
    a = y
if z%2 != 0 & (z > a):
    a = z
print(z%2 != 0 & (z > a))
print(z%2 != 0 and (z > a))
print(a)

The output was

True
False
7

Why do you get different outputs for & and "and". Aren't they the same?

I was reading that & is checking the actual bits of the value in question while and is evaluating the expression. Also & is supposed to be a "lazy" form of checking.

1

There are 1 best solutions below

2
ARslan Ahmad On

&& is the logical AND operator.

It can combine two boolean expressions and returns true if both expressions are true, otherwise, false. It's used for logical operations.

& is a bitwise AND operator.

It performs a bitwise AND operation on each bit of its operands. It is typically used for manipulating individual bits within integer values.