如何确定错误的数据类型

2024-10-02 20:32:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用下面的代码来查看数据是否是整数,如果不是,它会告诉我。有没有一种方法来确定哪一个是不正确的,以便可以更改它,还是我必须为每个项目创建相同的循环?你知道吗

while i_input == True:
    try:
        i_pointstarget=int(pointstarget.get())
        i_ap1=int(ap1.get())
        i_ap2=int(ap2.get())
        i_ap3=int(ap3.get())
        i_ap4=int(ap4.get())
        i_ap5=int(ap5.get())
        i_ap6=int(ap6.get())
    except ValueError:
        i_input=False
        continue
    else:
        break

感谢您的帮助:)


Tags: 数据项目方法代码inputget整数int
2条回答

除了尝试转换成int(顺便说一句int(1.23)工作,返回1)之外,还可以使用numberslike

import numbers
def is_integral(n): # actually not checking for int but also other int-equivalents
    return isinstance(n,numbers.Integral)

如果您想检查您是否有一个可以有损地转换为整数的数字(如int),您可以这样做

import numbers
def exact_integral(n): # check if n can be exactly represented as an integer
    return isinstance(n,numbers.Complex) and n==round(n.real)

要知道变量的类型,可以使用isinstance(variable_name, int),这将返回布尔值。你知道吗

相关问题 更多 >