1

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?

Steve_I
  • 31
  • 2

3 Answers3

2

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

cyberbemon
  • 3,000
  • 11
  • 37
  • 62
1

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.

qfwfq
  • 2,416
  • 1
  • 17
  • 30
0

If you want to use is you should do:

>>> print (type(x) is int)
True
coder
  • 12,832
  • 5
  • 39
  • 53
  • Thank you everyone for helping me understand Python's 'is' operator. I had read that 'is' could be used to check whether an identifier is of a specific type. Thank you coder for showing me the correct syntax for doing so. – Steve_I Sep 29 '16 at 15:45