I would like to be able to tell if a variable is an int or not using an if statement in Python. How would I go about this.
Asked
Active
Viewed 349 times
0
-
There are no variables in Python, there are only objects and references to objects – eyquem Feb 07 '11 at 08:20
-
3@eyquem: There is no need to be formal here. Of course there are variables in Python, the term is used many times throughout the official documentation, e.g. http://docs.python.org/tutorial/introduction.html#numbers ("The equal sign ('=') is used to assign a value to a variable"). – Ferdinand Beyer Feb 07 '11 at 08:42
-
4The next question is: Why do you need to do that? Usually you shouldn't need to do any type checking in Python. [Use "duck typing" instead](http://stackoverflow.com/questions/1549801/differences-between-isinstance-and-type-in-python/1549854#1549854). – Tim Pietzcker Feb 07 '11 at 08:59
-
@Tim Pietzcker: Thanks for pointing. I've deleted my answer. – Mudassir Feb 07 '11 at 09:44
4 Answers
5
Use isinstance
:
if isinstance(var, int):
print "Int"
elif isinstance(var, str):
print "Str"
else:
print "Other:", type(var)

Ferdinand Beyer
- 64,979
- 15
- 154
- 145
2
You just need to use isinstance:
value = 123
if isinstance(value, int):
print "Int"
else:
print "Not Int"

Richard J
- 6,883
- 4
- 22
- 27
0
If the question is to detect if a variable in bound to an int
or a value of any derived type, so isinstance
is the solution...
... but it does not distinguish between say int
and bool
.
In Python 3:
>>> isinstance(123, int)
True
>>> isinstance(True, int)
True
>>> isinstance(123, bool)
False
>>> isinstance(True, bool)
True
If you really need to know if a value is an int
and nothing else, type()
should be the way to go:
>>> type(123)
<class 'int'>
>>> type(123) == int
True

Sylvain Leroux
- 50,096
- 7
- 103
- 125