- Проверка на число
- isdigit, isnumeric и isdecimal
- Проверка с помощью исключения
- Для целых чисел
- 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()
Проверка на число
Достаточно часто требуется узнать: записано ли в переменной число. Такая ситуация может возникнуть при обработке введенных пользователем данных. При чтении данных из файла или при обработке полученных данных от другого устройства.
В Python проверка строки на число можно осуществить двумя способами:
- Проверить все символы строки что в них записаны цифры. Обычно используется для этого функция isdigit.
- Попытаться перевести строку в число. В Python это осуществляется с помощью методов float и int. В этом случае обрабатывается возможное исключение.
Рассмотрим как применяются эти способы на практике.
isdigit, isnumeric и isdecimal
У строк есть метод isdigit, который позволяет проверить, являются ли символы, являются ли символы, из которых состоит строка цифрами. С помощью этого метода мы можем проверить, записано ли в строку целое положительное число или нет. Положительное — это потому, что знак минус не будет считаться цифрой и метод вернет значение False.
a = '0251' print(a.isdigit()) True
Если в строка будет пустой, то функция возвратит False.
Методы строки isnumeric и isdecimal работают аналогично. Различия в этих методах только в обработке специальных символов Unicode. А так как пользователь будет вводить цифры от 0 до 9, а различные символы, например, дробей или римских цифр нас не интересуют, то следует использовать функцию isdigit.
Проверка с помощью исключения
Что же делать, если требуется проверить строку на отрицательное число. В Python с помощью isdigit не удастся определить отрицательное число или число с плавающей точкой. В этом случае есть универсальный и самый надежный способ. Надо привести строку к вещественному числу. Если возникнет исключение, то значит в строке записано не число.
Приведем функцию и пример ее использования:
def is_number(str): try: float(str) return True except ValueError: return False a = '123.456' print(is_number(a)) True
Для целых чисел
Аналогично можно сделать и проверку на целое число:
def is_int(str): try: int(str) return True except ValueError: return False a = '123.456' print(is_int(a)) False
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