Как найти целое число в python

To check if a float value is a whole number, use the float.is_integer() method:

>>> (1.0).is_integer()
True
>>> (1.555).is_integer()
False

The method was added to the float type in Python 2.6.

Take into account that in Python 2, 1/3 is 0 (floor division for integer operands!), and that floating point arithmetic can be imprecise (a float is an approximation using binary fractions, not a precise real number). But adjusting your loop a little this gives:

>>> for n in range(12000, -1, -1):
...     if (n ** (1.0/3)).is_integer():
...         print n
... 
27
8
1
0

which means that anything over 3 cubed, (including 10648) was missed out due to the aforementioned imprecision:

>>> (4**3) ** (1.0/3)
3.9999999999999996
>>> 10648 ** (1.0/3)
21.999999999999996

You’d have to check for numbers close to the whole number instead, or not use float() to find your number. Like rounding down the cube root of 12000:

>>> int(12000 ** (1.0/3))
22
>>> 22 ** 3
10648

If you are using Python 3.5 or newer, you can use the math.isclose() function to see if a floating point value is within a configurable margin:

>>> from math import isclose
>>> isclose((4**3) ** (1.0/3), 4)
True
>>> isclose(10648 ** (1.0/3), 22)
True

For older versions, the naive implementation of that function (skipping error checking and ignoring infinity and NaN) as mentioned in PEP485:

def isclose(a, b, rel_tol=1e-9, abs_tol=0.0):
    return abs(a - b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)

I would like to determine if a numeric value in Python is a whole number. For example, given:

y = x / 3

I want to distinguish between values of x which are evenly divisible by 3 those which are not.

Ron Zhang's user avatar

Ron Zhang

1951 gold badge3 silver badges17 bronze badges

asked Jun 4, 2011 at 23:17

johntheripper's user avatar

5

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

not float(your_number).is_integer()

answered Jun 4, 2011 at 23:22

Artur Gaspar's user avatar

Artur GasparArtur Gaspar

4,3971 gold badge26 silver badges28 bronze badges

2

if x % 3 == 0:
    print 'x is divisible by 3'

answered Jun 4, 2011 at 23:22

interjay's user avatar

interjayinterjay

106k21 gold badges267 silver badges251 bronze badges

6

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

answered Oct 31, 2011 at 14:23

Magnus Ribsskog's user avatar

1

Here’s another method:

x = 1/3  # insert your number here
print((x - int(x)) == 0)  # True if x is a whole number, False if it has decimals.

This works because int(x) essentially takes the floor of the number (ex. 3.6453 -> 3). If there’s something left over once you subtract the floor, it can’t have been a whole number.

answered Jan 25, 2017 at 1:10

Sakeeb Hossain's user avatar

x % 3 == 0 will be True if x / 3 is an integer.

answered Jun 4, 2011 at 23:22

Andrew Clark's user avatar

Andrew ClarkAndrew Clark

201k34 gold badges272 silver badges304 bronze badges

assuming you mean if a string containing digits also has a decimal point:

Python 2.6.6 (r266:84292, Apr 20 2011, 11:58:30) 
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> number='123.4'
>>> '.' in number
True
>>> number='123'
>>> '.' in number
False
>>>

To test if it’s integral you could mod 1:

>>> 1.0/3 % 1
0.33333333333333331
>>> 1/3 % 1
0

answered Jun 4, 2011 at 23:21

jcomeau_ictx's user avatar

jcomeau_ictxjcomeau_ictx

37.5k6 gold badges92 silver badges107 bronze badges

In Python 2, dividing an int by an int returns an int (unless python was invoked with the -Qnew option, or a from __future__ import division is at the beginning of the source; in that case / returns a float); a // specifies integer division.

In Python 3, dividing an int by an int returns a float if you use «/», or an int if you use «//».

If you want to know whether an int will divide into another int exactly, use «%» to look for a remainder.

tzot's user avatar

tzot

91.9k29 gold badges140 silver badges203 bronze badges

answered Jun 4, 2011 at 23:45

MRAB's user avatar

MRABMRAB

20.2k6 gold badges40 silver badges33 bronze badges

convert 1.0 => 1 & convert 1.x => 1.x

This code if float numbers has decimal part like 1.5 will return 1.5
& if it is 35.00 it return 35:

a = ReadFrom()    
if float(a).is_integer(): # it is an integer number like 23.00 so return 23
       return int(a)
 else: # for numbers with decimal part like : 1.5 return 1.5
       return float(a)

answered Jul 14, 2019 at 11:51

Hamed Jaliliani's user avatar

It is best to make your determination before doing the division, assuming that your x variable is an integer.

Trying to do equality tests or comparisons on floating point numbers is dangerous: http://www.lahey.com/float.htm

The answer already provided using modulus before doing the division to see if one integer is divsible by the other integer is safe. After you do a division and are dealing with possibly floating point values, then numbers are no longer exactly integers or not.

answered Jun 5, 2011 at 1:01

Ivan Novick's user avatar

Ivan NovickIvan Novick

7452 gold badges8 silver badges12 bronze badges

В этом посте мы обсудим, как проверить, является ли переменная целым числом или нет в Python.

1. Использование isinstance() функция

Стандартное решение для проверки, является ли данная переменная целым числом или нет, использует isinstance() функция. Он возвращается True если первый аргумент является экземпляром второго аргумента.

if __name__ == ‘__main__’:

    x = 10

    isInt = isinstance(x, int)

    print(isInt)            # True

Скачать  Выполнить код

 
Вы также можете использовать числовые абстрактные базовые классы вместо конкретных классов. Чтобы проверить целочисленное значение, вы можете использовать numbers.Integral Класс Python:

import numbers

if __name__ == ‘__main__’:

    x = 10

    isInt = isinstance(x, numbers.Integral)

    print(isInt)            # True

Скачать  Выполнить код

2. Использование float.is_integer() функция

Если вам нужно рассмотреть числа с плавающей запятой со всеми нулями после запятой, рассмотрите возможность использования float.is_integer() функция. Он возвращается True если экземпляр с плавающей запятой конечен с целым значением и False в противном случае.

if __name__ == ‘__main__’:

    x = 10.0

    isInt = float(x).is_integer()

    print(isInt)            # True

Скачать  Выполнить код

3. Использование int() функция

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

if __name__ == ‘__main__’:

    x = 10.0

    isInt = int(x) == x

    print(isInt)            # True

Скачать  Выполнить код

Это все, что касается определения того, является ли переменная целым числом или нет в Python.

Спасибо за чтение.

Пожалуйста, используйте наш онлайн-компилятор размещать код в комментариях, используя C, C++, Java, Python, JavaScript, C#, PHP и многие другие популярные языки программирования.

Как мы? Порекомендуйте нас своим друзьям и помогите нам расти. Удачного кодирования :)

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: <class 'int'>

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")

Output

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.

#syntax:
float.is_integer()

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

In this post, we are going to learn how to Check number is an integer in Python by using some built-in functions.We will ask user to input a number and check the type of input based on that return True or False.

5 Ways to Check number is integer in Python


  • type() :use type() function to check input numer is int or float
  • isinstance(): use to check if number is int or float
  • is_integer() : check float input is integer
  • check if input number is integer using Regular Expression
  • check string number is integer

1. Check input number is integer using type() function


In this example we are using built-in type() function to check if input number is integer or float.The type function will return the type of input object in python.

input_num = eval(input("Please Enter input :"))

if type(input_num) ==int:
    print("Number is integer:",type(input_num))
    
if type(input_num) ==float:
    print("Number is not integer",type(input_num))

Output

Please Enter input :112
Number is integer: <class 'int'>

2. Check number is integer using isinstance()


Python inbuilt isinstance() function check if number has type integer.The isinstance() function return true if given object of specified type.In this example we are checking if input_num object is of specified type int,float.

input_num = eval(input("Please Enter input :"))

print("Number is integer:",isinstance(input_num,int))
    
print("Number is float:",isinstance(input_num,float))

Output

Please Enter input :45
Number is integer: True
Number is float: False

3. check float number is integer using is_integer()


The is_integer() function return true if float value is finite with integer value otherwise return false.

input_num = eval(input("Please Enter float input :"))

print("Number is integer:",input_num.is_integer())

Output

Please Enter float input :45.9
Number is integer: False

4. Check input number is integer Using Regex


In this Python program example, we have defined a regular expression to check if input number is integer.The regular expression check the input number and return true and false.

  • If input number is integer it will return true
  • if input number is not integer it will return False.
import re

input_num = input("Please Enter input :")

reg_exp = re.compile(r'^-?[1-9][0-9]*$')
is_int = re.match(reg_exp,input_num)

if is_int:
    print("Number is integer:")
else:
    print("Number is not integer")

Output

Please Enter input :45.9
Number is not integer

5. Check string number is integer


Sometimes we have an integer number as a string. In this python code example we are checking if the input string number is integer.

  • First we have converted input value to float using the float() function.
  • Secondly used the is_integer() function to check if it is integer.
def check_str_isInt(input_num):
    try:
        float(input_num)
    except ValueError:
        return False
    else:
        return float(input_num).is_integer()

input_num = input("Please Enter input :")

print(check_str_isInt(input_num))

Output

Please Enter input :56.7
False

Please Enter input :'34'
False

Summary

In this post we have learned multiple ways of how to Check number is integer in Python using built in function type(),is_integer(),isinstance()

Понравилась статья? Поделить с друзьями:
  • Как составить маршрут в китай
  • Как найти файл образ windows
  • Как найти периметр правильного восьмиугольника
  • Как найти файл по расширению linux
  • Как исправить ошибку с разрешением экрана в играх