- Check if a number is int or float [duplicate]
- 19 Answers 19
- Python: проверка, является ли переменная числом
- Использование функции type()
- numbers.Number
- Использование блока try-except
- String.isnumeric()
- String.isdigit()
- How to check if a number is an integer in python?
- Check if a number is an integer using the type() function
- Check if a number is an integer using the isinstance() function
- Checking if a floating-point value is an integer using is_integer() function
- Checking if a floating-point value is an integer using split() + replace()
Check if a number is int or float [duplicate]
The trick is to search on SO for all the other times this question was asked. Each of those will provide a repeat of the same, standard answer.
assert isinstance(inNumber, (int, float)), «inNumber is neither int nor float, it is %s» % type(inNumber) was what I was looking for when I found this question with Google.
The questions is not particularly well put. Is the OP asking: 1) «What is the intrinsic Python variable type of the variable somenumber ?» 2) Is somenumber a whole number? 3) Is somenumber a string that is known to represent a number, but is does it represent an integer or floating point value? Some COUNTER CASES would help respondents suggest a suitable solution.
19 Answers 19
>>> x = 12 >>> isinstance(x, int) True >>> y = 12.0 >>> isinstance(y, float) True
>>> if isinstance(x, int): print('x is a int!') x is a int!
In case of long integers, the above won’t work. So you need to do:
>>> x = 12L >>> import numbers >>> isinstance(x, numbers.Integral) True >>> isinstance(x, int) False
@David: issubclass would be an error, as it works on classes. isinstance checks if a given object is an instance of a class or one of that class’s subclasses, so it’s perfectly generic. Methinks that isinstance(obj, cls) is equivalent to issubclass(obj.__class__, cls)
This doesn’t work for other integer types, for example if x = 12L . I know only int was asked for, but it’s nice to fix other problems before they happen. The most generic is probably isinstance(x, numbers.Integral) .
I like @ninjagecko’s answer the most.
isinstance(n, (int, long, float))
there is also type complex for complex numbers
A sidenote, because booleans will resolve to True (e.g. isinstance(False, (int, float)) = True ), I needed not isinstance(n, bool) and isinstance(n, (int, float)) instead
(note: this will return True for type bool , at least in cpython, which may not be what you want. Thank you commenters.)
isinstance(yourNumber, numbers.Real)
This avoids some problems:
>>> import numbers >>> someInt = 10 >>> someLongInt = 100000L >>> someFloat = 0.5 >>> isinstance(someInt, numbers.Real) True >>> isinstance(someLongInt, numbers.Real) True >>> isinstance(someFloat, numbers.Real) True
You can use modulo to determine if x is an integer numerically. The isinstance(x, int) method only determines if x is an integer by type:
def isInt(x): if x%1 == 0: print "X is an integer" else: print "X is not an integer"
@dylnmc Then you can use the isinstance() method to determine if x is a number. Also, 3.2 % 1 yields 0.2. If a number is evenly divisible by 1, it is an integer numerically. This method was useful to me even though it may not have been for you.
this is true; x%1 == 0 should be true for only ints (but it will also be true for floats with only a zero following decimal point). If you know it’s going to be an int (eg, if this is a param to a function), then you could just check with modulo. I bet that is faster than Math.floor(x) == x . On the not-so-bright side, this will be True if you pass a float like 1.0 or 5.0 , and you will encounter the same problem using what the original poster mentioned in his/her question.
It’s easier to ask forgiveness than ask permission. Simply perform the operation. If it works, the object was of an acceptable, suitable, proper type. If the operation doesn’t work, the object was not of a suitable type. Knowing the type rarely helps.
Simply attempt the operation and see if it works.
inNumber = somenumber try: inNumberint = int(inNumber) print "this number is an int" except ValueError: pass try: inNumberfloat = float(inNumber) print "this number is a float" except ValueError: pass
Python: проверка, является ли переменная числом
В этой статье мы рассмотрим несколько примеров того, как проверить, является ли переменная числом в Python.
Python имеет динамическую типизацию. Нет необходимости объявлять тип переменной во время ее создания — интерпретатор определяет тип во время выполнения:
variable = 4 another_variable = 'hello'
Кроме того, переменную можно переназначить новому типу в любой момент:
# Присвойте числовое значение variable = 4 # Переназначить строковое значение variable = 'four'
Этот подход, имея преимущества, также знакомит нас с несколькими проблемами. А именно, когда мы получаем переменную, мы обычно не знаем, какого она типа. Если мы ожидаем число, но получаем неопределенный variable , мы захотим проверить, является ли он числом, прежде чем выполнять какие-то действия.
Использование функции type()
В Python функция type() возвращает тип аргумента:
myNumber = 1 print(type(myNumber)) myFloat = 1.0 print(type(myFloat)) myString = 's' print(type(myString))
Таким образом, способ проверки типа:
myVariable = input('Enter a number') if type(myVariable) == int or type(myVariable) == float: # Do something else: print('The variable is not a number')
Здесь мы проверяем, является ли тип переменной, введенной пользователем, int или float , продолжая выполнение программы, если это так. В противном случае мы уведомляем пользователя, что он ввел переменную, отличную от Number. Помните, что если вы сравниваете несколько типов, например int или float , вам придется использовать эту type() функцию оба раза.
Если бы мы просто сказали if type(var) == int or float , что вроде бы нормально, возникла бы проблема:
myVariable = 'A string' if type(myVariable) == int or float: print('The variable a number') else: print('The variable is not a number')
Это, независимо от ввода, возвращает:
Это потому, что Python проверяет значения истинности утверждений. Переменные в Python могут быть оценены как True за исключением False , None , 0 и пустых [] , <> , set() , () , » или «» .
Следовательно, когда мы пишем or float в нашем условии, это эквивалентно записи or True , которая всегда будет возвращать True .
numbers.Number
Хороший способ проверить, является ли переменная числом — это модуль numbers . Вы можете проверить, является ли переменная экземпляром класса Number , с помощью функции isinstance() :
import numbers variable = 5 print(isinstance(5, numbers.Number))
Примечание. Этот подход может неожиданно работать с числовыми типами вне ядра Python. Некоторые фреймворки могут иметь нечисловую реализацию Number , и в этом случае этот подход вернет ложный результат False .
Использование блока try-except
Другой способ проверить, является ли переменная числом — использовать блок try-except. В блоке try мы преобразуем данную переменную в int или float . Успешное выполнение блока try означает, что переменная является числом, то есть либо int , либо float :
myVariable = 1 try: tmp = int(myVariable) print('The variable a number') except: print('The variable is not a number')
Это работает как для int, так и для float, потому что вы можете привести int к float и float к int.
Если вы специально хотите только проверить, является ли переменная одной из них, вам следует использовать функцию type() .
String.isnumeric()
В Python isnumeric() — это встроенный метод, используемый для обработки строк. Методы issnumeric() возвращают «True», если все символы в строке являются числовыми символами. В противном случае он возвращает «False».
Эта функция используется для проверки, содержит ли аргумент все числовые символы, такие как: целые числа, дроби, нижний индекс, верхний индекс, римские цифры и т.д. (Все написано в юникоде)
string = '123ayu456' print(string.isnumeric()) string = '123456' print( string.isnumeric())
String.isdigit()
Метод isdigit() возвращает истину, если все символы являются цифрами, в противном случае значение False.
Показатели, такие как ², также считаются цифрами.
print("\u0030".isdigit()) # unicode for 0 print("\u00B2".isdigit()) # unicode for ²
How to check if a number is an integer in python?
In mathematics, integers are the number that can be positive, negative, or zero but cannot be a fraction. For example, 3, 78, 123, 0, -65 are all integer values. Some floating-point values for eg. 12.00, 1.0, -21.0 also represent an integer. This article discusses various approaches to check if a number is an integer in python.
Check if a number is an integer using the type() function
In Python, we have a built-in method called type() that helps us to figure out the type of the variable used in the program. The syntax for type() function is given below.
#syntax: type(object) #example type(10) #Output:
In the following example, we declare a function check_integer to check if a number num is an integer value or not. The program checks if the type(num) is equal to the int datatype. If the condition returns True if block is executed. Otherwise, else block is executed.
def check_integer(num): if type(num) == int: print("Integer value") else: print("Not an Integer value") check_integer(14) #Positive Integer check_integer(-134) #Negative Integer check_integer(0) #Zero Value check_integer(345.87) #Decimal values
The above code returns the output as
Integer value Integer value Integer value Not an Integer value
Check if a number is an integer using the isinstance() function
The isinstance() method is an inbuilt function in python that returns True if a specified object is of the specified type. Otherwise, False. The syntax for instance() function is given below.
#syntax: isinstance(obj, type)
In the following example, we declare a function check_integer to check if a number num is an integer value or not. The program checks if the num is of int data type using the isinstance(num, int) function. If the condition is True if block is executed, Otherwise else block is executed.
def check_integer(num): if isinstance(num, int): print("Integer value") else: print("Not an Integer value") check_integer(14) #Positive Integer check_integer(-134) #Negative Integer check_integer(0) #Zero value check_integer(345.87) #Decimal value
The above code returns the output as
Integer value Integer value Integer value Not an Integer value
The number such as 12.0, -134.00 are floating-point values, but also represent an integer. If these values are passed as an argument to the type() or isinstance() function, we get output as False.
if type(12.0)== int: print("Integer value") else: print("Not an Integer value")
Checking if a floating-point value is an integer using is_integer() function
In python, the is_integer() function returns True if the float instance is a finite integral value. Otherwise, the is_integer() function returns False. The syntax for is_integer() function is given below.
In the following example, we declare a function check_integer to check if a floating-point number f is an integer value or not. If the f.is_integer() function evaluates to True, if block is executed. Otherwise, else block is executed.
def check_integer(f): if f.is_integer(): print("Integer value") else: print("Not a Integer value") check_integer(12.00) check_integer(134.23)
The above code returns the output as
Integer value Not a Integer value
Checking if a floating-point value is an integer using split() + replace()
In the following example, we declare a function check_integer to check if a number num is an integer value or not. The program checks if the type(int) is equal to the integer data type. If the condition is True if block is executed.
If the condition is False, the number is a floating-point value, and hence else block is executed. In the else block, we check if the float instance is a finite integral value. Consider a number num = 12.0. The number num also represents an integer.
We convert the number num to string data type using str() function and store it in the variable str_num = ‘12.0’. The string str_num is splitted from decimal point and is assigned to the variable list_1 = [’12’, ‘0’]. The element at position 1 of list_1 gives the decimal part of the number and is stored in variable ele.
We replace every ‘0’ character in the string ele with a blank space and assign the result to variable str_1. If the length of the str_1 is 0, then the floating instance is also an integer.
def check_integer(num): if type(num) == int: print("Integer value") else: str_num = str(num) list_1 = str_num.split('.') ele = list_1[1] str_1 = ele.replace('0', '') if len(str_1) == 0: print("Integer value") else: print("Not an integer value") check_integer(12.0) check_integer(13.456)
The above code returns the output as
Integer value Not an integer value