Проверьте, является ли переменная целым числом или нет в Python
В этом посте мы обсудим, как проверить, является ли переменная целым числом или нет в Python.
1. Использование isinstance() функция
Стандартное решение для проверки, является ли данная переменная целым числом или нет, использует isinstance() функция. Он возвращается True если первый аргумент является экземпляром второго аргумента.
Вы также можете использовать числовые абстрактные базовые классы вместо конкретных классов. Чтобы проверить целочисленное значение, вы можете использовать numbers.Integral Класс Python:
2. Использование float.is_integer() функция
Если вам нужно рассмотреть числа с плавающей запятой со всеми нулями после запятой, рассмотрите возможность использования float.is_integer() функция. Он возвращается True если экземпляр с плавающей запятой конечен с целым значением и False в противном случае.
3. Использование int() функция
Наконец, вы можете использовать конструктор int для проверки целочисленных значений. Функция int(x) преобразует аргумент x до целого числа. Если x уже является целым числом или числом с плавающей запятой с целым значением, то выражение int(x) == x будет соответствовать действительности.
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.
Please enable JavaScript
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.
The above code returns the output as
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.
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.
The above code returns the output as
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.
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.
The above code returns the output as
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.
Determining variable type
![]()
You can check what type of object is assigned to a variable using Python’s built-in type() function. Common data types include:
- int (for integer)
- float
- str (for string)
- list
- tuple
- dict (for dictionary)
- set
- bool (for Boolean True/False)
_is used as because we can’t use space in the name, use _instead
Python is a case—sensitive language.
This means Variable and variable are not the same. Always name identifiers that make sense.
While, c = 10 is valid.
- List[] :- Collection of elements can be changed (mutable).
- Tuple():- Collection of elements can’t be changed (immutable).
- Set<> :- Collection of unique elements. Sets do not allow repetition
Python has the following data types built-in by default, in these categories:
Numeric Types: int , float , complex
Sequence Types: list , tuple , range
Mapping Type: dict
Set Types: set , frozenset
Boolean Type: bool
Binary Types: bytes , bytearray , memoryview
Here is a simple code which can make you understand better
The following code example would print the data type of x, what data type would that be?
One should not use space in between my and income surely it will show the syntax
The output “int”(integer type)
For the above-given codes, we can assign a value called a & b respectively
Assigning Variables
Variable assignment follows name = object , where a single equals sign = is an assignment operator
Reassigning Variables
Python lets you reassign variables with a reference to the same object.
There’s actually a shortcut for this. Python lets you add, subtract, multiply and divide numbers with reassignment using += , -= , *= , and /= .
Setting the Specific Data Type
If you want to specify the data type, you can use the following constructor functions:
Rukovodstvo
статьи и идеи для разработчиков программного обеспечения и веб-разработчиков.
Python: проверьте, является ли переменная числом
Введение В этой статье мы рассмотрим несколько примеров того, как проверить, является ли переменная числом в Python. Python имеет динамическую типизацию. Нет необходимости объявлять тип переменной во время ее создания — интерпретатор определяет тип во время выполнения: variable = 4 another_variable = 'hello' Кроме того, переменную можно переназначить новому типу в любой момент времени: # Назначьте числовое значение value variable = 4 # Переназначить строковое значение переменной = 'four'. Этот подход при наличии рекламы
Время чтения: 3 мин.
Вступление
В этой статье мы рассмотрим несколько примеров того, как проверить, является ли переменная числом в Python.
Python имеет динамическую типизацию. Нет необходимости объявлять тип переменной при ее создании — интерпретатор определяет тип во время выполнения:
Кроме того, переменную можно переназначить новому типу в любой момент времени:
Этот подход, имея преимущества, также знакомит нас с несколькими проблемами. А именно, когда мы получаем переменную, мы обычно не знаем, какого она типа. Если мы ожидаем число, но получаем variable , мы захотим проверить, является ли это числом, прежде чем работать с ним.
Использование функции type ()
Функция type() в Python возвращает тип аргумента, который мы передаем ей, поэтому это удобная функция для этой цели:
Таким образом, способ проверки типа:
Здесь мы проверяем, является ли тип переменной, введенной пользователем, int или float , продолжая выполнение программы, если это так. В противном случае мы уведомляем пользователя о том, что он ввел нечисловую переменную. Имейте в виду, что если вы сравниваете несколько типов, например int или float , вы должны использовать type() оба раза.
Если бы мы просто сказали if type(var) == int or float , что, казалось бы, нормально, возникла бы проблема:
Это, независимо от ввода, возвращает:
Это потому, что Python проверяет значения истинности утверждений. Переменные в Python могут быть оценены как True за исключением False , None , 0 и пустых контейнеров, таких как [] , <> , set() , () , » или "" .
Следовательно, когда мы пишем or float в нашем if , это эквивалентно написанию or True которое всегда будет оцениваться как True .
числа.
Хороший способ проверить, является ли переменная числом, — это модуль numbers Вы можете проверить, является ли переменная экземпляром Number , с помощью функции isinstance() :
Примечание. Этот подход может неожиданно работать с числовыми типами вне ядра Python. Определенные структуры могут иметь не- Number реализации числовой, в этом случае этот подход будет ложно возвращать значение False .
Использование блока try-except
Другой способ проверить, является ли переменная числом, — использовать блок try-except. В блоке try мы приводим данную переменную к int или float . Успешное выполнение try означает, что переменная является числом, т.е. int или float :
Это работает как для int и для float потому что вы можете привести int к float и float к int .
Если вы конкретно хотите только проверить, является ли переменная одной из них, вам следует использовать функцию type()
Заключение
Python — это язык с динамической типизацией, что означает, что мы можем получить тип данных, отличный от того, который мы ожидаем.
В тех случаях, когда мы хотим принудительно применять типы данных, стоит проверить, имеет ли переменная желаемый тип. В этой статье мы рассмотрели три способа проверить, является ли переменная числом в Python.