1

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.

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
rawm
  • 251
  • 5
  • 24
  • 5
    `>>` and `<<` are bitshift operators, not comparison operators, which would be `>` and `<` if that is what you were *expecting* – juanpa.arrivillaga Jul 03 '19 at 00:47
  • 1
    The title and the question are not all that closely related to each other. You don't really care about how `if` works internally; you care about why `50 << 6` has the result it does. – Charles Duffy Jul 03 '19 at 00:53
  • @CharlesDuffy only because the asker has misdiagnosed the issue... – Shadow Jul 03 '19 at 00:54
  • 1
    @Shadow, ...exactly, because they didn't follow the instructions to isolate the simplest possible case. Removing `if` and testing `50 << 6` is part of building a properly minimal [mre]. – Charles Duffy Jul 03 '19 at 00:55

2 Answers2

5

<< 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")
rma
  • 1,853
  • 1
  • 22
  • 42
0

"<<" 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.

Edward Aung
  • 3,014
  • 1
  • 12
  • 15