1126

How do I check whether a variable is an integer?

Timur Shtatland
  • 12,024
  • 2
  • 30
  • 47
Hulk
  • 32,860
  • 62
  • 144
  • 215
  • 3
    @Hulk: You seem to be under the impression that `type` is the right way to do this. It is (almost certainly) not. – Katriel Aug 17 '10 at 12:16
  • @katrielalex: if he had chosen my answer as the right one doesn't mean Hulk was under the impression you mention. There also is the `ValueError` exception way mentioned BEFORE the `type()`. – Jungle Hunter Aug 17 '10 at 13:37
  • @Hulk: I'm honestly not campaigning for you to accept my answer -- please do feel free to change it back to Ashish; he provided a perfectly valid and technically correct answer. I just wanted to make sure you'd read the rest of the advice on this page. – Katriel Aug 17 '10 at 13:44
  • @katrielalex: Ashish was right but coding scenarios needed the except clause and so then i changed my answer.No offense Ashish – Hulk Aug 17 '10 at 13:55
  • 2
    @Hulk: No offense taken. But to be clear, the only way you can catch an exception (that I know of) is by using an except clause. I suggested you catch the `TypeError` exception. – Jungle Hunter Aug 17 '10 at 16:54
  • 17
    This question is ambiguous, and the answers are accordingly divided. Some are answering how to check the type of a variable (5→True, 5.0→ False), while others are answering how to check that the value is an integer (5→True, 5.0→True, Fraction(5,1)→True, 5.4→False). Maybe the question and answers should be split up accordingly? – endolith May 10 '13 at 14:39
  • @S.Lott - I want to format my output, with "{:03.2e}".format(value) for floating point and str(value) for integers. – Bulwersator Apr 23 '14 at 10:36
  • Related: http://stackoverflow.com/questions/21583758/how-to-check-if-a-float-value-is-a-whole-number – Denilson Sá Maia Mar 27 '15 at 15:54
  • @S.Lott - there is a very valid reason for that - when you are writing tests and checking if your value is actualy Integer and where assertIsNone would not test the condition you would like to test. – Greg0ry Jul 23 '15 at 12:51
  • This is a totally valid question. Example: you're processing data in batches, and receiving a non-integer in one row will cause the entire batch to fail in a later stage. You want to identify the problem before an exception is raised (and possibly raise your own exception). – elplatt May 19 '16 at 14:09
  • 1
    The most simple way (which works in Python 2.7.11) is int(var) == var. Works with .0 floats, returns boolean. – oisinvg Oct 21 '17 at 20:05
  • 2
    Do you mean "How do I determine if a variable's type is integer?" or "How do I determine if a variable's value is integer?" – Benice Oct 18 '19 at 17:28

41 Answers41

1370

If you need to do this, do

isinstance(<var>, int)

unless you are in Python 2.x in which case you want

isinstance(<var>, (int, long))

Do not use type. It is almost never the right answer in Python, since it blocks all the flexibility of polymorphism. For instance, if you subclass int, your new class should register as an int, which type will not do:

class Spam(int): pass
x = Spam(0)
type(x) == int # False
isinstance(x, int) # True

This adheres to Python's strong polymorphism: you should allow any object that behaves like an int, instead of mandating that it be one.

BUT

The classical Python mentality, though, is that it's easier to ask forgiveness than permission. In other words, don't check whether x is an integer; assume that it is and catch the exception results if it isn't:

try:
    x += 1
except TypeError:
    ...

This mentality is slowly being overtaken by the use of abstract base classes, which let you register exactly what properties your object should have (adding? multiplying? doubling?) by making it inherit from a specially-constructed class. That would be the best solution, since it will permit exactly those objects with the necessary and sufficient attributes, but you will have to read the docs on how to use it.

Community
  • 1
  • 1
Katriel
  • 120,462
  • 19
  • 136
  • 170
  • 8
    Hmm. I wonder about the BUT part! isn't proper and clear data checking on method input(e.g. start, before beginning to do anyting with a variable) good practice in python as it should generally be in any programming? So, for example, before I give data to a database query when wanting to fetch an objetc by id, which is an integer, I check if input is actually and integer and useable before handing it to the database layer. – Henning Jun 15 '13 at 09:49
  • 3
    @Henning I believe the "Pythonic" answer would be "no." By duck typing, it's only a problem if it would cause an error in the database level, and there's no way to tell if that's the case based on the type. So according to the BUT section, the best course of action would be to simply let the database layer throw the error and deal with it when it comes up. Anything with compatible behavior could be used; the `int`/`long` issue is a great example; what if someone has a custom `short` type? It's compatible with `int` and the database, but your code wouldn't accept it if it checked the type. – jpmc26 Jul 05 '13 at 23:01
  • 6
    @katrielalex This might sound stupid to you but can you explain to me why is `isinstance( True, int )` is returning True. – Nagri Nov 18 '13 at 08:04
  • 7
    Because Python `bool` (True, False) is a subclass of `int` =) It was a design decision of Python that booleans are just like integers, which goes hand in hand with the notion that any object can be evaluated as a boolean. – Katriel Nov 19 '13 at 15:09
  • 1
    Wouldn't it be best to use x += 0 in your try so as to not modify the int being "typed"? – DrBailey May 07 '15 at 17:48
  • 2
    @DrBailey could also just do ``x + 42`` with no assignment. Still valid python and doesn't modify anything. – Kasapo Jul 23 '15 at 18:22
  • This solution does not work when the soultion is a sting representing an integer (e.g is it was split out of a test string) - and we can't cast the variable to `int()` – Mawg says reinstate Monica Apr 14 '16 at 14:46
  • 1
    Note: this method will fail for some integer numbers types from numpy etc.: `isinstance(np.int16(33), int)` == False – kxr Aug 04 '16 at 12:34
  • In the presence of numpy extend to `isinstance(var, (int, long, np.integer))` for matching all variants. Recognizing ANY integer-like object from anywhere is a hard guess. Checking `var & 0 == 0` for truth and non-exception may be a good bet. – kxr Aug 04 '16 at 13:00
  • upvoted for your **big but**; flexibility is one of python's strengths and type checking kills it. – 7yl4r Apr 06 '18 at 17:09
  • @DrBailey You could also `try: number = (int)(number) except ValueError: ...` so you don't need to do any arithmetic. These "try" solutions are good for checking user input and argument variables as well so I think it is the best solution for OP. – deanresin Feb 24 '19 at 23:41
  • `try/except` worked without `TypeError` in Python 3: `try: key = int(sys.argv[1]) except: print("argument must be an integer")` – leanne Oct 01 '19 at 19:02
  • If you use the classical way and do x += 1 but x is a float, then it doesnt raise an error. Also, this modifies the data instead of just checking the type. Is this really the more elegant solution? – Flaming_Dorito Mar 04 '20 at 13:13
  • It does not work for the commonly used `numpy.ndarray`, there you should use: `issubclass(.dtype.type, np.integer)` as suggested here: https://stackoverflow.com/questions/934616/how-do-i-find-out-if-a-numpy-array-contains-integers – Nir Oct 18 '22 at 07:42
160

Here's a summary of the different methods mentioned here:

  • int(x) == x
  • try x = operator.index(x)
  • isinstance(x, int)
  • isinstance(x, numbers.Integral)

and here's how they apply to a variety of numerical types that have integer value:

Table of methods for checking whether Python numerical types are integers

You can see they aren't 100% consistent. Fraction and Rational are conceptually the same, but one supplies a .index() method and the other doesn't. Complex types don't like to convert to int even if the real part is integral and imaginary part is 0.

(np.int8|16|32|64(5) means that np.int8(5), np.int32(5), etc. all behave identically)

endolith
  • 25,479
  • 34
  • 128
  • 192
  • Your `sympy.Rational` test doesn't quite do what you're thinking, because `sympy.Rational(5)` evaluates to an instance of `sympy.Integer`. Any operation that would produce a Rational with an integer value instead produces an Integer. – user2357112 Jan 26 '19 at 19:23
  • @user2357112 How is that not "what I'm thinking"? – endolith Jan 27 '19 at 00:42
  • You say `sympy.Rational` supports `operator.index`, but it doesn't. What's going on is that `sympy` aggressively switches to more specific types. `sympy.Rational(5)` doesn't really fit under the "rational" subsection of the table. – user2357112 Jan 27 '19 at 02:29
  • @user2357112 But `Rational(5)` can't even exist. It's converted to `Integer` immediately, which does support `operator.index`. – endolith Jan 27 '19 at 02:51
  • We seem to both understand that, but it's not the message your answer conveys. – user2357112 Jan 27 '19 at 02:53
  • @user2357112 What message does my answer convey that is different from reality? `Rational(3, 5)` doesn't support `.__index__()`, but `sympy.Rational(5).__index__()` produces 5, since it's immediately converted to an `Integer`. – endolith Jan 27 '19 at 02:58
  • mind blowing explanation – Malith Ileperuma May 12 '20 at 17:57
  • I would think that anything that supports `operator.index()` should also be in `numbers.Integral`, no? Why wouldn't they be? – endolith Apr 16 '21 at 03:36
152

All proposed answers so far seem to miss the fact that a double (floats in python are actually doubles) can also be an integer (if it has nothing after the decimal point). I use the built-in is_integer() method on doubles to check this.

Example (to do something every xth time in a for loop):

for index in range(y): 
    # do something
    if (index/x.).is_integer():
        # do something special

Edit:

You can always convert to a float before calling this method. The three possibilities:

>>> float(5).is_integer()
True
>>> float(5.1).is_integer()
False
>>> float(5.0).is_integer()
True

Otherwise, you could check if it is an int first like Agostino said:

def is_int(val):
    if type(val) == int:
        return True
    else:
        if val.is_integer():
            return True
        else:
            return False
JakeD
  • 2,788
  • 2
  • 20
  • 29
saroele
  • 9,481
  • 10
  • 29
  • 39
  • 2
    Do you have a link to documentation for this `is_integer` function? I can't find one. – Gabe Apr 11 '13 at 21:30
  • 4
    There is not much, but here is the official documentation: http://docs.python.org/2/library/stdtypes.html#float.is_integer – saroele Apr 12 '13 at 08:41
  • 5
    That's good to know. Although, it's a `float` method, so it's not a general-purpose function that can be applied to any type to determine whether it's an integer. – Craig McQueen Sep 12 '13 at 23:50
  • 3
    First check if it's an `int` (or a `long`), then check if it's a `float` and, if it is, check if `is_integer()` is true. Notice that there is no `long` type in Python 3. – Agostino Apr 29 '15 at 18:44
  • @saroele the error I get thrown is as follows: `AttributeError: 'str' object has no attribute 'is_integer'` – 3kstc Jan 08 '18 at 03:36
  • @3kstc if your object is not a number this will indeed fail. You tried this on a string object, and `str` does not have the method `is_integer`. You could put the function in a `try...except` and catch an `AttributeError`. If the error is catched, your object was not a `float`. – saroele Jan 18 '18 at 09:29
  • 6
    `int(x) == x` covers floats, too. – endolith Feb 22 '18 at 21:01
  • This should have more upvotes. I've been dealing with this use-case more often than the accepted answer's – Nathan majicvr.com Jun 23 '18 at 00:55
70

If you really need to check then it's better to use abstract base classes rather than concrete classes. For an integer that would mean:

>>> import numbers
>>> isinstance(3, numbers.Integral)
True

This doesn't restrict the check to just int, or just int and long, but also allows other user-defined types that behave as integers to work.

Scott Griffiths
  • 21,438
  • 8
  • 55
  • 85
  • 3
    `isinstance(Fraction(5,1), numbers.Integral)` → False. Is that right? – endolith Jun 30 '12 at 17:10
  • 6
    @endolith: My answer (and the others) say whether the variable's type is an integer rather than if the variable itself could be converted to an integer without losing information. So yes your example is `False`, in the same way as checking the 'integerness' of `5.00` would be. – Scott Griffiths Jun 30 '12 at 22:29
  • 3
    ... but I suppose you could also do an 'is this object exactly representable as an integer' test along the lines of `type(f)(int(f)) == f`. – Scott Griffiths Jun 30 '12 at 22:32
  • `isinstance(x, (type(1), type(2**32)))` would work in both Py 2.x and 3.x -- no abc class necessary. – martineau Jun 25 '13 at 19:37
  • 2
    @martineau: but that method doesn't get user-defined integer types which is the point of using the abstract base class. Testing for particular numbers is definitely a hack - the obvious point to make is that the numbers you've chosen won't work for 64-bit Python 2.x. – Scott Griffiths Jun 26 '13 at 07:25
  • `isinstance()` returns true if its first argument is an instance of or the second or is a direct, indirect or virtual subclass thereof. As for 64-bit, just use at least `type(2**64)` for the second argument which would work with both 32- and 64-bit Python. – martineau Jun 26 '13 at 07:45
  • 1
    @martineau: but the type might not be a subclass of `int`, it might just represent integer numbers. An example would be the numpy `int16` type. Now admittedly this doesn't use the ABC either, but it could if it wanted to say it's an integer type of object but didn't want actually be an `int`. Oh and wait until they make a 128-bit Python build :) – Scott Griffiths Jun 26 '13 at 08:25
  • Hmmm...maybe [S.Lott](http://stackoverflow.com/a/3501475/355230) is right and doing any type-checking is absolutely wrong. However if one insists on doing it using `isinstance()`, it is possible to arbitrarily make _any_ class an ABC subclass as illustrated in this very interesting [answer](http://stackoverflow.com/questions/305359/correct-way-to-detect-sequence-parameter/306222#306222). – martineau Jun 26 '13 at 14:41
  • `isinstance(True, numbers.Integral)` return `True`. Should it though? – Leonid Jan 10 '14 at 05:52
  • @Leonid: Yes it should. `True` and `False` really are integers in Python - `issubclass(bool, int)` also returns `True`. – Scott Griffiths Jan 10 '14 at 10:31
  • Does not work for `numpy.int32` integers! Oddly, it does work for `numpy.int64` integers. – Quant Metropolis Dec 09 '14 at 12:40
  • 1
    This is a great answer, because `isinstance(numpy.int64(0), int) == False` in Python 3. – quant_dev Jul 22 '19 at 12:19
40
>>> isinstance(3, int)
True

See here for more.

Note that this does not help if you're looking for int-like attributes. In this case you may also want to check for long:

>>> isinstance(3L, (long, int))
True

I've seen checks of this kind against an array/index type in the Python source, but I don't think that's visible outside of C.

Token SO reply: Are you sure you should be checking its type? Either don't pass a type you can't handle, or don't try to outsmart your potential code reusers, they may have a good reason not to pass an int to your function.

Matt Joiner
  • 112,946
  • 110
  • 377
  • 526
  • +1: After all, `decimal.Decimal` and `fractions.Rational` often works where you've so carefully checked for `int`. Type checking in advance prevents **legal, appropriate** use. It doesn't prevent any problems. – S.Lott Aug 17 '10 at 11:05
  • 1
    I had a variable in a dictionary so have to do a type check in this case – Hulk Aug 17 '10 at 12:06
  • 2
    @Hulk: Why is that case special? – Katriel Aug 17 '10 at 12:17
  • The requirement was such that if value of the variable is not a integer then not to process further.. – Hulk Aug 17 '10 at 13:41
  • Are you sure that's the requirement? What if somebody makes a `loggedInt` that logs every time it's accessed (!)... shouldn't you accept that as well? – Katriel Aug 17 '10 at 13:43
  • 3
    @Hulk: "if value of the variable is not a integer then not to process further" Best handled by exception surrounding the loop. This does not need any type checking. – S.Lott Aug 17 '10 at 14:20
  • Of course you should be checking its type (either by isinstance, or exception handling). Yes a user might have a good reason to do it. But he might have a bad reason to do it (or just be stupid, as is often the case) as well, and you need to guard against that. In a perfect world AGE> could be answered "Nearly fifty" but on a budget you probably don't have time to implement near perfect AI! – Shayne Nov 04 '13 at 06:00
  • 1
    isinstance(False, int) True – Frutik Oct 03 '19 at 14:15
29

Why not try something like:

if x%1 == 0: 
Noelkd
  • 7,686
  • 2
  • 29
  • 43
Parsa
  • 1,137
  • 1
  • 11
  • 15
  • 8
    -1 because this is not code I would want to see in production or by my teammates. It hides your intention. Most of the other answers here are much more explicit and should be preferred. – Dennis Nov 05 '14 at 00:37
  • 24
    @Dennis: but this works also for floats with decimal part equal to zero. You can wrap it in a function and it will be explicit. – Marco Sulla Apr 18 '16 at 12:06
  • What if `x` is not even a number, say a string? – Jason Sep 04 '17 at 07:49
  • The original question is not quite specific enough and is being interpreted in two ways; @Hulk could remove the ambiguity by asking either: "How do I determine if a variable's type is integer?" or "How do I determine if a variable's value is integer?" Voting either interpretation down is not really fair. – Benice Oct 18 '19 at 17:18
19

Rather than over complicate things, why not just a simple

if type(var) is int:
Dairy Window
  • 1,307
  • 1
  • 13
  • 9
  • 5
    Don't use type() as it won't always work, use isinstance() instead. See the answer above http://stackoverflow.com/a/3501408/2574719 – goetz Jul 26 '16 at 18:11
15

A simple method I use in all my software is this. It checks whether the variable is made up of numbers.

test = input("Enter some text here: ")
if test.isdigit() == True:
   print("This is a number.")
else:
   print("This is not a number.")
Resin Drake
  • 528
  • 4
  • 9
  • 2
    This works for vars that are strings, but crashes for vars that are already digits (isdigit() is a string method in python). – shacker Aug 10 '15 at 21:02
  • Also `isdigit` returns `False` for negative numbers and floats: `'-10'.isdigit()` and `'1.5'.isdigit()`. – Anton Tarasenko Oct 14 '18 at 12:10
15

You can also use str.isdigit. Try looking up help(str.isdigit)

def is_digit(str):
      return str.isdigit()
Fariman Kashani
  • 856
  • 1
  • 16
  • 29
13

Found a related question here on SO itself.

Python developers prefer to not check types but do a type specific operation and catch a TypeError exception. But if you don't know the type then you have the following.

>>> i = 12345
>>> type(i)
<type 'int'>
>>> type(i) is int
True
Community
  • 1
  • 1
Jungle Hunter
  • 7,233
  • 11
  • 42
  • 67
  • 3
    -1 You should at the very least explain why not to do this. Just posting this code promotes bad Python. (I hate to downvote this, because it's technically correct, but it shouldn't be upvoted.) – Katriel Aug 17 '10 at 10:25
  • There you go. You would be glad to notice it is not up-voted now either. – Jungle Hunter Aug 17 '10 at 10:37
  • Thanks. Downvote removed. (Though you could be a bit more emphatic about not using `type` =p.) – Katriel Aug 17 '10 at 10:39
12

it's really astounding to see such a heated discussion coming up when such a basic, valid and, i believe, mundane question is being asked.

some people have pointed out that type-checking against int (and long) might loose cases where a big decimal number is encountered. quite right.

some people have pointed out that you should 'just do x + 1 and see whether that fails. well, for one thing, this works on floats too, and, on the other hand, it's easy to construct a class that is definitely not very numeric, yet defines the + operator in some way.

i am at odds with many posts vigorously declaring that you should not check for types. well, GvR once said something to the effect that in pure theory, that may be right, but in practice, isinstance often serves a useful purpose (that's a while ago, don't have the link; you can read what GvR says about related issues in posts like this one).

what is funny is how many people seem to assume that the OP's intent was to check whether the type of a given x is a numerical integer type—what i understood is what i normally mean when using the OP's words: whether x represents an integer number. and this can be very important: like ask someone how many items they'd want to pick, you may want to check you get a non-negative integer number back. use cases like this abound.

it's also, in my opinion, important to see that (1) type checking is but ONE—and often quite coarse—measure of program correctness, because (2) it is often bounded values that make sense, and out-of-bounds values that make nonsense. sometimes just some intermittent values make sense—like considering all numbers, only those real (non-complex), integer numbers might be possible in a given case.

funny non-one seems to mention checking for x == math.floor( x ). if that should give an error with some big decimal class, well, then maybe it's time to re-think OOP paradigms. there is also PEP 357 that considers how to use not-so-obviously-int-but-certainly-integer-like values to be used as list indices. not sure whether i like the solution.

flow
  • 3,624
  • 36
  • 48
  • 1
    Some of the use cases for such a test involve treating an integer as a special case; for that, you can just be prepared for `x==math.floor(x)` or `x == int(x)` to raise an exception, and then treat that as "no". But other use cases involve wanting to get an early, clearer exception rather than a more confusing one later, when a non-integer parameter just doesn't make sense. We have an assortment of answers to this question, for different use cases. – greggo Jul 06 '15 at 19:08
8

If you want to check that a string consists of only digits, but converting to an int won't help, you can always just use regex.

import re
x = "01234"
match = re.search("^\d+$", x)
try: x = match.group(0)
except AttributeError: print("not a valid number")

Result: x == "01234"

In this case, if x were "hello", converting it to a numeric type would throw a ValueError, but data would also be lost in the process. Using a regex and catching an AttributeError would allow you to confirm numeric characters in a string with, for instance, leading 0's.

If you didn't want it to throw an AttributeError, but instead just wanted to look for more specific problems, you could vary the regex and just check the match:

import re
x = "h01234"
match = re.search("\D", x)
if not match:
    print("x is a number")
else:
    print("encountered a problem at character:", match.group(0))

Result: "encountered a problem at character: h"

That actually shows you where the problem occurred without the use of exceptions. Again, this is not for testing the type, but rather the characters themselves. This gives you much more flexibility than simply checking for types, especially when converting between types can lose important string data, like leading 0's.

sudokode
  • 81
  • 1
  • 1
  • No need for regex to do that: `all(ch in set(string.digits) for ch in x)`, but as pointed out elsewhere on this page, it's a bad method anyway. – Thijs van Dien Nov 24 '12 at 20:48
7

why not just check if the value you want to check is equal to itself cast as an integer as shown below?

def isInt(val):
    return val == int(val)
NotNamedDwayne
  • 585
  • 1
  • 6
  • 10
  • 3
    need to enclose (or replace) the test with a `try/except` block, or it will throw exception if `val` is, for example, `'a'` – MestreLion May 14 '13 at 05:55
  • 1
    Could replace with `return val == int(val)`, and the exception block is needed as MestreLion mentions. – jpmc26 Jul 13 '13 at 07:56
7

It is very simple to check in python. You can do like this:

Suppose you want to check a variable is integer or not!

## For checking a variable is integer or not in python

if type(variable) is int:
     print("This line will be executed")
else:
     print("Not an integer")
alexander.polomodov
  • 5,396
  • 14
  • 39
  • 46
premvardhan
  • 71
  • 1
  • 2
5

In the presence of numpy check like ..

isinstance(var, numbers.Integral)

.. (slow) or ..

isinstance(var, (int, long, np.integer))

.. in order to match all type variants like np.int8, np.uint16, ...

(Drop long in PY3)

Recognizing ANY integer-like object from anywhere is a tricky guessing game. Checking

var & 0 == 0 

for truth and non-exception may be a good bet. Similarly, checking for signed integer type exclusively:

var ^ -1 ==  -var - 1
kxr
  • 4,841
  • 1
  • 49
  • 32
5

Here is a simple example how you can determine an integer

def is_int(x):
    print round(x),
    if x == round(x):
        print 'True',
    else:
        print 'False'

is_int(7.0)   # True
is_int(7.5)   # False
is_int(-1)    # True    
V-rund Puro-hit
  • 5,518
  • 9
  • 31
  • 50
PradeepNama
  • 511
  • 6
  • 6
5

If you are reading from a file and you have an array or dictionary with values of multiple datatypes, the following will be useful. Just check whether the variable can be type casted to int(or any other datatype you want to enforce) or not.

try :
    int(a);
    #Variable a is int
except ValueError : 
    # Variable a is not an int
tranquil
  • 499
  • 7
  • 13
4

If the variable is entered like a string (e.g. '2010'):

if variable and variable.isdigit():
    return variable #or whatever you want to do with it. 
else: 
    return "Error" #or whatever you want to do with it.

Before using this I worked it out with try/except and checking for (int(variable)), but it was longer code. I wonder if there's any difference in use of resources or speed.

Ramon Suarez
  • 309
  • 3
  • 12
4

A simple way to do this is to directly check if the remainder on division by 1 is 0 or not.

if this_variable % 1 == 0:
    list.append(this_variable)
else:
    print 'Not an Integer!'
hiteshn97
  • 97
  • 3
  • 10
  • This will not work if the variable is for example a string. You would need to catch the exception, etc. Better see http://stackoverflow.com/a/3501408/2574719 – goetz Jul 26 '16 at 18:06
3

use the int function to help

intchecker = float(input('Please enter a integer: '))
intcheck = 0
while intcheck != 1:
    if intchecker - int(intchecker) > 0:
        intchecker = float(input("You didn't enter a integer. "
                                 "Please enter a integer: "))
    else:
        intcheck = 1
print('you have entered a integer')
Chillar Anand
  • 27,936
  • 9
  • 119
  • 136
the noob
  • 31
  • 1
3

If you just need the value, operator.index (__index__ special method) is the way to go in my opinion. Since it should work for all types that can be safely cast to an integer. I.e. floats fail, integers, even fancy integer classes that do not implement the Integral abstract class work by duck typing.

operator.index is what is used for list indexing, etc. And in my opinion it should be used for much more/promoted.

In fact I would argue it is the only correct way to get integer values if you want to be certain that floating points, due to truncating problems, etc. are rejected and it works with all integral types (i.e. numpy, etc.) even if they may not (yet) support the abstract class.

This is what __index__ was introduced for!

seberg
  • 8,785
  • 2
  • 31
  • 30
  • Seems to be just the thing. Odd thing though: it accepts True and False but doesn't map them to 1 and 0, it returns the same value (using py2.7). It could be that's because bool is a subclass of int and that's considered good enough for an index. You can always do `int(operator.index(x))` to ensure a real int. – greggo Jul 06 '15 at 19:00
3

If you want to check with no regard for Python version (2.x vs 3.x), use six (PyPI) and it's integer_types attribute:

import six

if isinstance(obj, six.integer_types):
    print('obj is an integer!')

Within six (a very light-weight single-file module), it's simply doing this:

import sys
PY3 = sys.version_info[0] == 3

if PY3:
    integer_types = int,
else:
    integer_types = (int, long)
Nick T
  • 25,754
  • 12
  • 83
  • 121
2

I was writing a program to check if a number was square and I encountered this issue, the code I used was:

import math
print ("this program will tell you if a number is square")
print ("enter an integer")
num = float(input())
if num > 0:
    print ("ok!")
    num = (math.sqrt(num))
    inter = int(num)
    if num == inter:
            print ("It's a square number, and its root is")
            print (num)
    else:
            print ("It's not a square number, but its root is")
            print (num)
else:
    print ("That's not a positive number!")

To tell if the number was an integer I converted the float number you get from square rooting the user input to a rounded integer (stored as the value ), if those two numbers were equal then the first number must have been an integer, allowing the program to respond. This may not be the shortest way of doing this but it worked for me.

Community
  • 1
  • 1
Tom
  • 21
  • 1
  • That doesn't seem like a correct algorithm, since it will fail for integers bigger than what a float mantissa can hold. Try it with `12345678901234567890123456789012` (which is not a square) and see if it gives the right answer. You should implement an integer square root algorithm instead. – Craig McQueen Sep 13 '13 at 00:04
  • See [this question](http://stackoverflow.com/questions/15390807/integer-square-root-in-python) regarding integer square roots. – Craig McQueen Sep 13 '13 at 00:18
2

You can do this.

if type(x) is int:
2
#!/usr/bin/env python

import re

def is_int(x):

    if(isinstance(x,(int,long))):

        return True
    matchObj = re.match(r'^-?\d+\.(\d+)',str(x))

        if matchObj:

        x = matchObj.group(1)

        if int(x)-0==0:

            return True

     return False

print is_int(6)

print is_int(1.0)

print is_int(1.1)

print is_int(0.1)

print is_int(-956.0)
Math
  • 3,334
  • 4
  • 36
  • 51
Ben
  • 21
  • 2
2

If you have not int you can do just this:

var = 15.4
if(var - int(var) != 0):
    print "Value is not integer"
Luke359
  • 447
  • 6
  • 14
  • This will not work if the variable is for example a string. You would need to catch the exception, etc. Better see http://stackoverflow.com/a/3501408/2574719 – goetz Jul 26 '16 at 18:08
2

If you want to write a Python 2-3 compatible code

To test whether a value is an integer (of any kind), you can to do this :

# Python 2 and 3: 
import sys
if sys.version_info < (3,):
    integer_types = (int, long,)
else:
    integer_types = (int,)

>>> isinstance(1, integer_types)
True

# Python 2 only:
if isinstance(x, (int, long)):
     ...

# Python 3 only:
if isinstance(x, int):
    ...

source : http://python3porting.com/differences.html

Community
  • 1
  • 1
2

A more general approach that will attempt to check for both integers and integers given as strings will be

def isInt(anyNumberOrString):
    try:
        int(anyNumberOrString) #to check float and int use "float(anyNumberOrString)"
        return True
    except ValueError :
        return False

isInt("A") #False
isInt("5") #True
isInt(8) #True
isInt("5.88") #False *see comment above on how to make this True
jcchuks
  • 881
  • 8
  • 16
1

you can do this by:

name = 'Bob'
if type(name) == str:
    print 'this works'
else:
    print 'this does not work'

and it will return 'this works'... but if you change name to int(1) then it will return 'this does not work' because it is now a string... you can also try:

name = int(5)
if type(name) == int:
    print 'this works'
else:
    print 'this does not work'

and the same thing will happen

1

There is another option to do the type check.

For example:

  n = 14
  if type(n)==int:
  return "this is an int"
Vijaya Pandey
  • 4,252
  • 5
  • 32
  • 57
Kyle Cheng
  • 11
  • 2
1

Consider the case x = n**(1.0/m), where n=10**5, m=5. In Python, x will be 10.000000000000002, which is only not integer because of floating point arithmetic operations.

So I'd check

if str(float(x)).endswith('.0'): print "It's an integer."

I've tested it with this code:

for a in range(2,100):
    for b in range(2,100):
        x = (a**b)**(1.0/b)
        print a,b, x, str(float(x)).endswith('.0')

It outputs True for all a and b.

  • Seems like thin ice. The behaviour of str(float) has changed in the past, in ways that could affect this. In any case the number is not equal to 10, just close enough for 'str' to call it. You could check abs(x-round(x)) if you are OK with rounding fuzz. – greggo Jun 21 '15 at 03:06
1
#######################################
# Value_Is_Int
#######################################
def value_is_int(value):
    try:
        tempVal = int(value)
        return True
    except:
        return False

Call this function:

if value_is_int(value):
    print "Integer"
else:
    print "Not integer"
Guray Celik
  • 1,281
  • 1
  • 14
  • 13
1

I can check if the number is integer include number like 7.0

def is_int(x):
    if x - round(x) == 0 :
        return True
    else:
        return False
Community
  • 1
  • 1
1
if type(input('enter = '))==int:
     print 'Entered number is an Integer'
else:
     print 'Entered number isn't an Integer'

This'll work to check out whether number is an integer or not

Prashant Shukla
  • 742
  • 2
  • 6
  • 19
1
val=3
>>> isinstance(val,int ) 
True

will work.

Saurabh
  • 7,525
  • 4
  • 45
  • 46
1

Testing, if object is a string (works with Python 2.* and Python 3.* )

text = get_text()

try:
    text = text+""
except:
    return "Not a string"

do_something(text)
Mika72
  • 413
  • 2
  • 12
1

The simplest way is:

if n==int(n):
    --do something--    

Where n is the variable

Youssef Ahmed
  • 162
  • 1
  • 5
-2
import numpy as np

if (np.floor(x)-x == 0):
  return "this is an int"
user2983638
  • 903
  • 1
  • 13
  • 20
-2

You can use this function:

def is_int(x):    
    if type(x) == int:
       return True
    return False

Test:

print is_int('7.0') # False
print is_int(7.0) # False
print is_int(7.5) # False
print is_int(-1) # True
Michael Qin
  • 629
  • 6
  • 10
  • Don't use type(), use isinstance(), see the answer above http://stackoverflow.com/a/3501408/2574719 – goetz Jul 26 '16 at 18:02
-5

I've had this problem before, if your type to use it in a if statement, and let's just say you wanted it to return true, you would enter this into a line, (The bottom line in all that is really needed to be looked at):

In [1]: test = 1

In [2]: test2 = 1.0

In [3]: type(test) == int
Out[3]: True

In [4]: type(test2) == int
Out[4]: False

In [5]: if type(x) == int is True:

You can do the same thing to check if it's a float, if it's true or false, and use to assign a name, (like x if you know what I mean.)

maxshuty
  • 9,708
  • 13
  • 64
  • 77
Clay
  • 1
  • 3
    What does your answer add to existing answers? `if type(x) == int is True` is *terribly* wrong, i.e. it will always evaluate to `False`. – vaultah Nov 17 '16 at 16:07
-7

Never. Check. Types.

Do this. Always.

try:
    some operation that "requires" an integer
except TypeError, e:
    it wasn't an integer, fail.
S.Lott
  • 384,516
  • 81
  • 508
  • 779
  • 5
    It is sometimes necessary to check the type of the object (as you admit in your comment above). Although it's usually misguided there are real use-cases and the language provides the facilities to do it. I don't think that saying never ever do something is helpful or correct. – Scott Griffiths Aug 17 '10 at 10:35
  • Can you think of a single instance where you *must* check the type of an object? With the advent of ABCs I think they are probably now gone. – Katriel Aug 17 '10 at 10:37
  • 1
    Certainly in terms of efficiency and readable code, yes type checking has proved invaluable to me. For example in an initialiser that takes different types not doing an explicit check can lead to some convoluted and computationally expensive code. I can't really provide a good example in a comment though! – Scott Griffiths Aug 17 '10 at 10:47
  • 1
    @Scott Griffiths. That's the only counter example. That's why I said "never". It's always important to use universals to force people to think. It's never appropriate to waffle around about special cases. – S.Lott Aug 17 '10 at 10:53
  • 4
    @Scott Giffiths: Also, "in terms of efficiency" is likely false. Please measure carefully. Except clauses are remarkably efficient. – S.Lott Aug 17 '10 at 10:59
  • 5
    The efficiency argument isn't just in terms of single statements. I agree that try/except is very efficient and isinstance() is remarkably slow (I have profiled quite a lot). Sometimes to distinguish between, for example, a string and another type of iterable you might have go some way before an exception gets raised (if an exception gets raised at all!) So the time lost is in going half-way through the try clause before being able to bail out. This can also be quite a fragile arrangement and you run the risk that a later change might make the exception not be raised. – Scott Griffiths Aug 17 '10 at 11:15
  • 1
    @Scott Griffiths: Limiting things to a narrow range of types "can also be quite a fragile arrangement". Someone creates a new type that's perfectly legal, yet prohibited by needless up-front type checking. "you might have go some way before an exception gets raised" is hard to envision without a specific example. – S.Lott Aug 17 '10 at 12:21
  • As Scott Griffiths made the statement "a string and another type of iterable you might have go some way before an exception gets raised (if an exception gets raised at all!) So the time lost is in going half-way through the try clause before being able to bail out" There was a scenario as exactly described to be handled if a variable is not integer why process further.... – Hulk Aug 17 '10 at 13:38
  • @S.Lott :i agree your except clause statement – Hulk Aug 17 '10 at 13:40
  • @Hulk: "So the time lost is in going half-way through the try clause before being able to bail out" There is still no actual example of this. I expect that this is trivially preventable without resorting to needless type checking. But without an actual example, I can't correct the error that leads to "going half-way through the try clause before being able to bail out". – S.Lott Aug 17 '10 at 14:18
  • @S.Lott:The example i cangive of u is this.I am constructing a dictionary from reading a file row..After reading this and processing it i create another dictionary of the desired values.So for example for reading every line in a file i construct two dictionaries. so if one of the field is not integer i return an exception in which case i dont have to construct the second dictionary dictionary..I hope u understand now.. – Hulk Aug 17 '10 at 18:48
  • @Hulk: First, an `if` statement doesn't help you check the type. An exception works **faster** than an `if` statement. Second, you can build two dictionaries together, not build one dictionary and then build a second dictionary. The example is not good. – S.Lott Aug 17 '10 at 19:09
  • @S.Lott I know this is a bit old, but you want an example? How about me using an external library that is doing a REST call to another server. It looks up a order number (int) but the input could be a string, in that case I want to look up a redemption token instead. The external libraries will not fail if I give them the wrong type but they will be slow (seconds) in returning a result saying {'status': 'failed'} or something like that. Do you still think it's a bad idea to check the type? :) – olofom May 29 '12 at 08:41
  • 3
    What if the code still works (incorrectly) with non-ints, though, and that's what I'm trying to prevent? – endolith Jun 30 '12 at 17:08
  • 1
    You dismiss @ScottGriffiths counterexample which, if valid, disproves your "never", with 'That's the only counter example. That's why I said "never"'. Seriously? Do you realize you're baiting people and wasting their time? – Don Hatch May 18 '16 at 04:03