Steve_I
Steve_I

Reputation: 31

Python Boolean comparison

I'm testing Python's Boolean expressions. When I run the following code:

x = 3
print type(x)
print (x is int)
print (x is not int)

I get the following results:

<type 'int'>
False
True

Why is (x is int) returning false and (x is not int) returning true when clearly x is an integer type?

Upvotes: 1

Views: 302

Answers (3)

qfwfq
qfwfq

Reputation: 2526

Try typing these into your interpreter:

type(x)
int
x is 3
x is not 3
type(x) is int
type(x) is not int

The reason that x is int is false is that it is asking if the number 3 and the Python int class represent the same object. It should be fairly clear that this is false.

As a side note, Python's is keywords can work in some unexpected ways if you don't know exactly what it is doing, and you should almost certainly be avoiding it if you are ever testing equality. That being said, experimenting with it outside of your actual program is a very good idea.

Upvotes: 1

coder
coder

Reputation: 12992

If you want to use is you should do:

>>> print (type(x) is int)
True

Upvotes: 0

cyberbemon
cyberbemon

Reputation: 3200

The best way to do this is use isinstance()

so in your case:

x = 3
print isinstance(x, int)

Regarding python is

The operators is and is not test for object identity: x is y is true if and only if x and y are the same object.

Taken from docs

Upvotes: 2

Related Questions