Reputation: 299
I was just trying out a simple if statement and it doesn't work as expected. Is there an error on my part or is there something about if statement's functioning that I'm ignorant of?
the code is:
i = 50
n = 6
if i >> n:
print("I is greater")
elif i << n:
print("I is lesser")
elif i == n:
print("I and N are same")
else:
print("no result")
the output is "I is lesser" even if i put a greater or equal value. Please help me understand how this works.
Upvotes: 1
Views: 121
Reputation: 3512
"<<" is bit-wise shift left. It is somewhat equivalent to multiplying by 2 for the right-operand times.
">>" is bit-wise shift right. It is somewhat equivalent to dividing by 2 for the right operand times.
In your example "50 << 6" means shift-left 50, which is 110010 in binary (1 * 32 + 1 * 16 + 0 * 8 + 1 * 2 + 0 * 1 = 50), 6 times. Therefore, it becomes 110010000000 = 3200. Non-zero numbers (such as 3200) is evaluate to True in python.
Again, "50 >> 6" means shift-left 110010 to left 6 times. It becomes 11001 after shift-left once, 1100 after shift-left twice ... and become 0 after shift-left for 6 times.
Zero number is evaluate to False in python.
Upvotes: 0
Reputation: 1958
<<
and >>
are bitshift operators, not comparison operators. 50 >> 6
is 0
, so that if statement is evaluating to false because it is falsy. 50 << 6
is 3200, so that if statement is evaluating to true, because it is truthy.
This code may work the way you 'expect' it to
i = 50
n = 6
if i > n:
print("I is greater")
elif i < n:
print("I is lesser")
elif i == n:
print("I and N are same")
else:
print("no result")
Upvotes: 5