-4

What is happening here?

x = 5

x >>= 3

print(x)

the output is 0 and I can't understand why.

Roxana Sh
  • 294
  • 1
  • 3
  • 14
  • 3
    `x` right shift by 3 bits and assign back to `x`. `>>` is the right shift bit-wise operation. It's a shorthand similar to `x =+ 2` means `x = x + 2`. – fiveelements Aug 10 '19 at 12:14
  • 1
    just like `x += 3` is the same as `x = x + 3` . And then instead of the `+` you have a bitwise shift `>>` operator. This comment + the dupe link should explain everything for ya. – Paritosh Singh Aug 10 '19 at 12:15
  • @ParitoshSingh It made me confused, thank you for your description. – Roxana Sh Aug 10 '19 at 12:23

2 Answers2

1

It's a shorthand for x = x >> 3. Since 5 >> 3 is 0 you get 0 as a result.

The operator >> is a right shift:

>>> bin(5)
'0b101'
>>> bin(5 >> 1)
'0b10'
>>> bin(5 >> 2)
'0b1'
>>> bin(5 >> 3)
'0b0'
mensi
  • 9,580
  • 2
  • 34
  • 43
0

This is basically a right shift operator. Bit Pattern of the data can be shifted by specified number of Positions to Right

5 in bits = 101

101 >> 3. It will return zero.

Ishan Arora
  • 124
  • 1
  • 6