TypeError:' float' object不能解释为整数

时间:2015-09-21 03:42:19

标签: python if-statement floating-point typeerror

为什么对象被解释为int而不是float。

main2 = True

while main2:
     try:
        amount = float(input('annual gross income: '))
        namount = float(amount)
        expenses = float(input('annual expenses: '))
        nnexpenses = float(expenses)



        if(9226 <= namount <= 37450):
                print('Your tax rate is  $922.50 + 15%')
                print(float(round(namount - namount*0.15 - 922.50 - nnexpenses)))
        if(namount <= 9225):
                print('Your tax rate is 10%')
                print(float(round(namount - namount*0.10 - nnexpenses,2)))
        if(37451 <= namount <= 90750 ):
                print('Your tax rate is  $5, 156.25 + 25%')
                print(float(round(amount - namount*0.25 - 5,156.25 - nnexpenses)))
        if(90751 <= namount <= 189300):
                 print('Your tax rate is  $18,481.25 + 28%')
                 print(float(round(amount - namount*0.28 - 18,481.25 - nnexpenses))) 
        if(189301 <= namount <= 411500):
                print('Your tax rate is  $46,075.25 + 33%')
                print(float(round(namount - namount*0.33 - 46,075.25 - nnexpenses)))
        if(411501 <= namount <= 413200):
                 print('Your tax rate is  $119,401.25 + 35%')
                 print(float(round(namount - namount*0.35 - 119,401.25 - nnexpenses)))
        if(413201 <= namount):
                 print('Your tax rate is  $119,996.25 + 39.6%')
                 print(float(round(namount - namount*0.396 - 119,996.25 - nnexpenses)))

        #print('Annual Net Income: ', round(result,2))
     except(ValueError,NameError):
         #if(ValueError):
         print('Please enter a number and postive balance.')
         #else:
             #print('Get out of debt')

3 个答案:

答案 0 :(得分:3)

从您的号码中删除逗号。逗号被解释为参数分隔符,意味着使用两个参数而不是一个参数调用round

print(float(round(namount - namount*0.35 - 119,401.25 - nnexpenses)))

应该是

print(float(round(namount - namount*0.35 - 119401.25 - nnexpenses)))

答案 1 :(得分:1)

问题是您传递的浮点数是round()的第二个参数。一个非常简单的测试用例来重现这个问题 -

>>> round(1.5,1.5)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'float' object cannot be interpreted as an integer

来自documentation -

  

round(number [,ndigits])

     

将浮点值数字舍入为小数点后的数字位数。如果省略ndigits,则默认为零。

ndigits需要是一个整数,它表示小数点后的位数。

但你在做 -

print(float(round(amount - namount*0.25 - 5,156.25 - nnexpenses)))

我猜你试图用逗号表示数字,但这不是Python接受它的方式,如果5,156.25是数字5156.25,那么你需要删除逗号。

答案 2 :(得分:0)

您收到此错误是因为您在值中使用逗号,例如:5,156.25 - 对于Python,这不是“五千一百五十六十进制二五”。< / p>

由于您已将其添加到对round的调用中,因此将逗号后面的部分添加为第二个参数。

您的电话是:

round(5, 156.25)

这将引发错误。

从您的值中删除逗号,您应该得到您期望的结果。