Pavan Manjunath
Pavan Manjunath

Reputation: 28545

TypeError: bad operand type for unary ~: 'long' in Python

I am from a C background and hence this problem in Python really confounds me

Consider this

print ~(1 << 1)

This correctly prints -3.

Consider this

print ~(1 << 0)

This flags an error like

TypeError: bad operand type for unary ~: 'long'

I checked for various other positive values of shift count and it works fine. Only a shift count of zero doesn't seem to work. All similar posts on unary operators that I found on SO dealt with other operators like +, - etc but not ~

I just dabble in Python every now and then, so I may be missing something silly but googling dint help much

PS: I ran this on codeskulptor which is probably using Python 2.7, I am not sure though

EDIT: This turns out to be a bug in Codeskulptor. I wrote a mail to Prof Rixner who's the main developer to take note of this bug. Thanks all.

Upvotes: 0

Views: 1355

Answers (2)

Ethan Furman
Ethan Furman

Reputation: 69190

This is an error with CodeSkulptor's implementation.

If you force the value back to int, it works:

print ~(int(1 << 0))

Okay, perhaps 'error' was too strong -- looking at their site they only claim to "implement a subset of Python 2".

Upvotes: 2

Brane Čibej
Brane Čibej

Reputation: 26

This works in both Python2 and Python3; to demonstrate:

$ python --version
Python 2.7.6
$ python -c 'print(~(1<<0))'
-2

$ python3 --version
Python 3.4.2
$ python3 -c 'print(~(1<<0))'
-2

Can you show a bit more of your script and explain which version (and which implementation!) of Python you're using?

Upvotes: 0

Related Questions