I'm new to Python and am trying to understand types. Specifically, can someone explain why I am getting these results?
>>> start = 1
>>> start is int
False
>>> type(start)
<class 'int'>
I ask, because I am trying to run a test in a script and can't understand why it is failing the test, and I am afraid to cast the input as an int because, if it isn't, I want to make sure it doesn't pass this test. here's the code:
def slice(self, start=0, stop=0, step=1):
if start != 0 and start is not int:
for item in self.data:
if start in item:
start = self.data.index(item)
But when I do this:
slice(1,10)
It fails the "start is not int" and drops into the for loop.
Any help, please?
You should do: isinstance(start, int)
.
start is int
checks whether start
is the type int
, not whether start
is an instance of the type int
.
>>> start = 1
>>> start is int
False
>>> isinstance(start, int)
True
From the Python 3 documentation:
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. x is not y yields the inverse truth value. [4]
start is 1 while int is a Python class. Here's some sample code that may help you:
>>> start = 1
>>> start is int
False
>>> start == int
False
>>> start is 1
True
>>> start == 1
True
>>> type(start) == int
True
You should use type() or isinstance() (as Simeon suggested).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.