Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking whether a variable is an integer or not [duplicate]

Tags:

python

integer

How do I check whether a variable is an integer?

like image 765
Hulk Avatar asked Aug 17 '10 10:08

Hulk


People also ask

How do you check if a variable is an integer?

isInteger() Method. The Number isInteger() method takes the variable as a parameter and returns the true if the variable is an integer. Otherwise, it returns false.

How do you check if a variable is an integer or string in Python?

Using isdigit() method we can check, whether the user entered input is a number or string. If it is a number then it will return the input is number else it will return input is a string.

How do you check if a variable is between two numbers?

Use the comparison operators to check if a number is between two numbers. Use the syntax minimum <= number <= maximum such that maximum is greater than minimum to return a boolean indicating whether number falls between minimum and maximum on a number line.

How do you check if it is integer or not in Python?

Python offers isnumeric() method that checks whether a string is an integer or not. This method is similar to the isdigit() method but with a few differences. The isnumeric() method checks whether all the characters in the string are numeric. While the isdigit() method checks whether the strings contain only digits.


1 Answers

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.

like image 155
Katriel Avatar answered Oct 09 '22 00:10

Katriel