问题:检查数字是否为int或float

这是我的做法:

inNumber = somenumber
inNumberint = int(inNumber)
if inNumber == inNumberint:
    print "this number is an int"
else:
    print "this number is a float"

这样的事情。
有没有更好的方法可以做到这一点?

Here’s how I did it:

inNumber = somenumber
inNumberint = int(inNumber)
if inNumber == inNumberint:
    print "this number is an int"
else:
    print "this number is a float"

Something like that.
Are there any nicer looking ways to do this?


回答 0

使用isinstance

>>> 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!

_编辑:_

如前所述,在长整数的情况下,上述方法不起作用。因此,您需要执行以下操作:

>>> x = 12L
>>> import numbers
>>> isinstance(x, numbers.Integral)
True
>>> isinstance(x, int)
False

Use isinstance.

>>> x = 12
>>> isinstance(x, int)
True
>>> y = 12.0
>>> isinstance(y, float)
True

So:

>>> if isinstance(x, int):
        print 'x is a int!'

x is a int!

_EDIT:_

As pointed out, 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

回答 1

我最喜欢@ninjagecko的回答。

这也将起作用:

对于Python 2.x

isinstance(n, (int, long, float)) 

Python 3.x时间不

isinstance(n, (int, float))

对于复数也有复数类型

I like @ninjagecko’s answer the most.

This would also work:

for Python 2.x

isinstance(n, (int, long, float)) 

Python 3.x doesn’t have long

isinstance(n, (int, float))

there is also type complex for complex numbers


回答 2

单线:

isinstance(yourNumber, numbers.Real)

这样可以避免一些问题:

>>> isinstance(99**10,int)
False

演示:

>>> import numbers

>>> someInt = 10
>>> someLongInt = 100000L
>>> someFloat = 0.5

>>> isinstance(someInt, numbers.Real)
True
>>> isinstance(someLongInt, numbers.Real)
True
>>> isinstance(someFloat, numbers.Real)
True

One-liner:

isinstance(yourNumber, numbers.Real)

This avoids some problems:

>>> isinstance(99**10,int)
False

Demo:

>>> import numbers

>>> someInt = 10
>>> someLongInt = 100000L
>>> someFloat = 0.5

>>> isinstance(someInt, numbers.Real)
True
>>> isinstance(someLongInt, numbers.Real)
True
>>> isinstance(someFloat, numbers.Real)
True

回答 3

要求宽恕比要求许可容易。只需执行操作即可。如果可行,则该对象属于可接受的,合适的适当类型。如果该操作无效,则该对象不是适当的类型。知道类型很少有帮助。

只需尝试该操作,看看它是否有效。

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

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

回答 4

您也可以使用type() 示例:

if type(inNumber) == int : print "This number is an int"
elif type(inNumber) == float : print "This number is a float"

What you can do too is usingtype() Example:

if type(inNumber) == int : print "This number is an int"
elif type(inNumber) == float : print "This number is a float"

回答 5

这是一段检查数字是否为整数的代码,它适用于Python 2和Python 3。

import sys

if sys.version < '3':
    integer_types = (int, long,)
else:
    integer_types = (int,)

isinstance(yourNumber, integer_types)  # returns True if it's an integer
isinstance(yourNumber, float)  # returns True if it's a float

请注意,Python 2具有int和的两种类型long,而Python 3仅具有和的类型int来源

如果要检查您的数字是否为float代表的数字int,请执行此操作

(isinstance(yourNumber, float) and (yourNumber).is_integer())  # True for 3.0

如果您不需要区分int和float,并且都可以,那么ninjagecko的答案就是解决方法

import numbers

isinstance(yourNumber, numbers.Real)

Here’s a piece of code that checks whether a number is an integer or not, it works for both Python 2 and Python 3.

import sys

if sys.version < '3':
    integer_types = (int, long,)
else:
    integer_types = (int,)

isinstance(yourNumber, integer_types)  # returns True if it's an integer
isinstance(yourNumber, float)  # returns True if it's a float

Notice that Python 2 has both types int and long, while Python 3 has only type int. Source.

If you want to check whether your number is a float that represents an int, do this

(isinstance(yourNumber, float) and (yourNumber).is_integer())  # True for 3.0

If you don’t need to distinguish between int and float, and are ok with either, then ninjagecko’s answer is the way to go

import numbers

isinstance(yourNumber, numbers.Real)

回答 6

这个解决方案怎么样?

if type(x) in (float, int):
    # do whatever
else:
    # do whatever

how about this solution?

if type(x) in (float, int):
    # do whatever
else:
    # do whatever

回答 7

我知道这是一个旧线程,但这是我正在使用的东西,我认为这可能会有所帮助。

它适用于python 2.7和python 3 <。

def is_float(num):
    """
    Checks whether a number is float or integer

    Args:
        num(float or int): The number to check

    Returns:
        True if the number is float
    """
    return not (float(num)).is_integer()


class TestIsFloat(unittest.TestCase):
    def test_float(self):
        self.assertTrue(is_float(2.2))

    def test_int(self):
        self.assertFalse(is_float(2))

I know it’s an old thread but this is something that I’m using and I thought it might help.

It works in python 2.7 and python 3< .

def is_float(num):
    """
    Checks whether a number is float or integer

    Args:
        num(float or int): The number to check

    Returns:
        True if the number is float
    """
    return not (float(num)).is_integer()


class TestIsFloat(unittest.TestCase):
    def test_float(self):
        self.assertTrue(is_float(2.2))

    def test_int(self):
        self.assertFalse(is_float(2))

回答 8

您可以使用模来确定x是否为整数。该isinstance(x, int)方法仅按类型确定x是否为整数:

def isInt(x):
    if x%1 == 0:
        print "X is an integer"
    else:
        print "X is not an integer"

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"

回答 9

在Python 3.6.3 Shell中试用

>>> x = 12
>>> import numbers
>>> isinstance(x, numbers.Integral)
True
>>> isinstance(x,int)
True

无法解决任何工作。

Tried in Python version 3.6.3 Shell

>>> x = 12
>>> import numbers
>>> isinstance(x, numbers.Integral)
True
>>> isinstance(x,int)
True

Couldn’t figure out anything to work for.


回答 10

请检查一下:进口号码

import math

a = 1.1 - 0.1
print a 

print isinstance(a, numbers.Integral)
print math.floor( a )
if (math.floor( a ) == a):
    print "It is an integer number"
else:
    print False

尽管X是浮点型,但值是整数,所以如果要检查值是整数,则不能使用isinstance,并且需要比较值而不是类型。

pls check this: import numbers

import math

a = 1.1 - 0.1
print a 

print isinstance(a, numbers.Integral)
print math.floor( a )
if (math.floor( a ) == a):
    print "It is an integer number"
else:
    print False

Although X is float but the value is integer, so if you want to check the value is integer you cannot use isinstance and you need to compare values not types.


回答 11

absolute = abs(x)
rounded = round(absolute)
if absolute - rounded == 0:
  print 'Integer number'
else:
  print 'notInteger number'
absolute = abs(x)
rounded = round(absolute)
if absolute - rounded == 0:
  print 'Integer number'
else:
  print 'notInteger number'

回答 12

更新:试试这个


inNumber = [32, 12.5, 'e', 82, 52, 92, '1224.5', '12,53',
            10000.000, '10,000459', 
           'This is a sentance, with comma number 1 and dot.', '121.124']

try:

    def find_float(num):
        num = num.split('.')
        if num[-1] is not None and num[-1].isdigit():
            return True
        else:
            return False

    for i in inNumber:
        i = str(i).replace(',', '.')
        if '.' in i and find_float(i):
            print('This is float', i)
        elif i.isnumeric():
            print('This is an integer', i)
        else:
            print('This is not a number ?', i)

except Exception as err:
    print(err)

Update: Try this


inNumber = [32, 12.5, 'e', 82, 52, 92, '1224.5', '12,53',
            10000.000, '10,000459', 
           'This is a sentance, with comma number 1 and dot.', '121.124']

try:

    def find_float(num):
        num = num.split('.')
        if num[-1] is not None and num[-1].isdigit():
            return True
        else:
            return False

    for i in inNumber:
        i = str(i).replace(',', '.')
        if '.' in i and find_float(i):
            print('This is float', i)
        elif i.isnumeric():
            print('This is an integer', i)
        else:
            print('This is not a number ?', i)

except Exception as err:
    print(err)

回答 13

您可以使用简单的if语句来完成此操作

检查浮球

如果type(a)== type(1.1)

检查整数类型

如果type(a)== type(1)

You can do it with simple if statement

To check for float

if type(a)==type(1.1)

To check for integer type

if type(a)==type(1)


回答 14

def is_int(x):
  absolute = abs(x)
  rounded = round(absolute)
  if absolute - rounded == 0:
    print str(x) + " is an integer"
  else:
    print str(x) +" is not an integer"


is_int(7.0) # will print 7.0 is an integer
def is_int(x):
  absolute = abs(x)
  rounded = round(absolute)
  if absolute - rounded == 0:
    print str(x) + " is an integer"
  else:
    print str(x) +" is not an integer"


is_int(7.0) # will print 7.0 is an integer

回答 15

试试这个…

def is_int(x):
  absolute = abs(x)
  rounded = round(absolute)
  return absolute - rounded == 0

Try this…

def is_int(x):
  absolute = abs(x)
  rounded = round(absolute)
  return absolute - rounded == 0

回答 16

variable.isnumeric 检查值是否为整数:

 if myVariable.isnumeric:
    print('this varibale is numeric')
 else:
    print('not numeric')

variable.isnumeric checks if a value is an integer:

 if myVariable.isnumeric:
    print('this varibale is numeric')
 else:
    print('not numeric')

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。