Целые числа питон проверка

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)

Читайте также:  Flexbox css две колонки

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 

Источник

Проверка на целое число

На ввод дается два чилса в одной строчке через пробел, Нужно проверить целые они или нет, если нет, то вывести:»Неправильный формат ввода». Вот мой код:

a, b = map(int, input().split()) if int(a)/float(a)==1.0: print('является целым числом') else: print('не целое число.') if int(b)/float(b)==1.0: print('является целым числом') else: print('не целое число.') 

2 ответа 2

Не такая простая задача если решать её полностью. Есть три с половиной варианта:

  1. целое число (0, -33, 16, 1_000_000)
    • вещественное число (0.1, -123.4, 12e-1, 12.345e2).
    • вещественное число c целым значением (1.0, -16.0, 12.34e2)
  2. непонятно что (123s, abracadabra, 1O0).

Целое число распознает int(s) . Если s строка с целым числом внутри, то вернётся его значение, иначе будет выброшено исключение ValueError .

Вещественное число распознает float(s) . И тоже выбросит исключение в случае неправильного формата.

Для проверки целочисленного значения вещественного числа пригодится метод is_integer .

В третий пункт попадает всё что вообще не выглядит как число.

Проверка на целое число должна идти до проверки на вещественное, иначе все целые числа будут записаны в вещественные.

def as_int(s): try: return int(s) except ValueError: return None def as_float(s): try: return float(s) except ValueError: return None def main(): s = input() i = as_int(s) if i is not None: print('int', repr(s), i) return f = as_float(s) if f is not None: print('float', repr(s), f) if f.is_integer(): print('. of integer value') return print('. ', repr(s)) main() 
$ python is_integer.py 1_000_000 int '1_000_000' 1000000 $ python is_integer.py 0 int '0' 0 $ python is_integer.py -33 int '-33' -33 $ python is_integer.py 16 int '16' 16 $ python is_integer.py 0.1 float '0.1' 0.1 $ python is_integer.py -123.4 float '-123.4' -123.4 $ python is_integer.py 12e-1 float '12e-1' 1.2 $ python is_integer.py 12.345e2 float '12.345e2' 1234.5 $ python is_integer.py 1.0 float '1.0' 1.0 . of integer value $ python is_integer.py -16.0 float '-16.0' -16.0 . of integer value $ python is_integer.py 12.34e2 float '12.34e2' 1234.0 . of integer value $ python is_integer.py 123s . '123s' $ python is_integer.py abracadabra . 'abracadabra' $ python is_integer.py 1O0 . '1O0' 

Источник

Determining whether an value is a whole number in Python

What do you mean by decimals in this case? An integer is an integer. It is always a whole number. Somehow it sounds like you want to check an integer for diseases: This integer has decimals, we have to bring it to the hospital! 😉

What do you mean by «decimals» in this context? Decimal point? Integers never have them (a number with a decimal point is parsed as a floating-point number).

I understand that by “integer” he means “number”, and by “decimals” he means “fractional part”, so I believe interjay’s answer is spot on.

The accepted answer does not answer the title. I came here through google trying to answer the title question. Since the poster has accepted an answer which differs from the title, can/should we edit the title? See related meta post. NOTE: If the title is fixed this becomes a duplicate question of this.

9 Answers 9

Integers have no decimals. If you meant «check if a number got decimals in Python», you can do:

not float(your_number).is_integer() 
if x % 3 == 0: print 'x is divisible by 3' 

@lev Part of answering questions here is understanding what the OP actually meant to ask. Read more than just the title of the question. Here it’s clear that the OP wanted to know how to tell if one number is divisible by another. Doing that by checking if the result of division is an integer is unpythonic and error-prone.

Important: this does not check if a number is a decimal, as the title and part of the question would suggest to be asking for. For example, if you have x == 0.3, the code above will print ‘x is divisible by 3’, but x is not a whole number. See Artur Gaspar answer for checking if a number is a decimal. @interjay this should do.

There is only one problem with the code at the moment. In Python, you are supposed to put parentheses around the stuff you are going to print. So the print bit of code should be print (‘x is divisible by 3’) . If not, you will still get an error.

It appears that the asking user didn’t initially specify the version he/she is using, nor does it appear in the question’s comments about discussion relating to Python 2 or 3. I had made a suggested edit about adding category Python 2 for clarification.

@Boris The asker wanted to know how to tell if a number is divisible by another. This answer is relevant to anyone with the same question. The fact that the title of the question asks something different is an instance of an XY problem. Literally answering that question would be counterproductive due to floating-point inaccuracies. In fact, using the other answer’s float(your_number).is_integer() to determine divisibility would lead to incorrect results in many cases. Please read the entire question before criticizing answers, not just the title.

Edit: As Ollie pointed out in the comment below this post, is_integer is part of the standard library and should therefore not be reimplemented as I did below.

This function uses the fact that every other whole number will have at least one number divisible by two with no remainder. Any non-zero fractional representation in either n or n+1 will cause both n%2 and (n+1)%2 to have a remainder. This has the benefit that whole numbers represented as float values will return True. The function works correctly for positive and negative numbers and zero as far as I can determine. As mentioned in the function, it fails for values very close to an integer.

def isInteger(n): """Return True if argument is a whole number, False if argument has a fractional part. Note that for values very close to an integer, this test breaks. During superficial testing the closest value to zero that evaluated correctly was 9.88131291682e-324. When dividing this number by 10, Python 2.7.1 evaluated the result to zero""" if n%2 == 0 or (n+1)%2 == 0: return True return False 

Источник

Проверка, является ли переменная целым числом

Часто при программировании на Python возникает необходимость проверить, является ли значение переменной целым числом. Это может быть полезно в различных ситуациях, например, при валидации пользовательского ввода или при обработке данных разного типа. Рассмотрим пример.

Если попытаться использовать это значение в математических операциях, возникнет ошибка, так как это строка, а не число. Для избежания таких ошибок и проводится проверка типа переменной.

Как проверить, является ли переменная целым числом

Python предоставляет встроенную функцию isinstance() , которая позволяет проверить, принадлежит ли объект к определенному классу или типу данных.

value = 123 print(isinstance(value, int))

В этом примере isinstance() вернет True , если значение является целым числом ( int ), и False в противном случае.

Проверка на целочисленность для чисел с плавающей точкой

Если работа ведется с числами с плавающей точкой ( float ), которые могут быть целыми, можно использовать метод is_integer() .

value = 123.0 print(value.is_integer())

В этом примере value.is_integer() вернет True , если число с плавающей точкой является целым числом, и False в противном случае.

Заключение

Проверка, является ли переменная целым числом, в Python — простая и полезная операция, которую можно легко реализовать с помощью встроенных функций и методов. Она помогает избежать ошибок при выполнении операций с переменными разных типов.

Источник

Оцените статью