为什么我的tax_a,b,c无法找到?

时间:2017-02-03 17:21:18

标签: python

目的是从用户那里获得收入,并根据用户赚取的金额应用一组税收。

income = float(input('Enter your income:  $ '))

if income < 35000:
    tax_a = float((income * 0.15))

if (income - 35000) < 100000:
    tax_b = float((income * 0.25))

if (income - 100000) > 100000:
    tax_c = float((income * 0.35))

if income > 50000:
    tax_s = (income * 0.05)

fed_tax = float((tax_a + tax_b + tax_c))
total_tax = (fed_tax + tax_s)

print('Your total tax liability is:  ${:.2f}'.format(total_tax))
print('[details Federal tax: {:.2f}, State tax: {:.2f}'.format(fed_tax, tax_s))

3 个答案:

答案 0 :(得分:1)

如果某些条件为真,您只定义tax_atax_btax_ctax_s。如果条件不为真,则保留变量undefined。

我不是税务律师,但如果条件不适用,我认为给定类别的税是0:

if income < 35000:
    tax_a = float((income * 0.15))
else:
    tax_a = 0.0

......等等。

答案 1 :(得分:0)

需要初始化变量并了解“变量范围”。

tax_a = tax_b = tax_c = tax_s = 0
income = float(input('Enter your income:  $ '))
# ...

答案 2 :(得分:0)

$ python incometax.py 
Enter your income:  $ 100000
Traceback (most recent call last):
  File "incometax.py", line 15, in <module>
    fed_tax = float((tax_a + tax_b + tax_c))
NameError: name 'tax_a' is not defined

问题是tax_a仅在某种情况发生时定义。由于在最终计算中总是需要这些变量,因此您应该在程序的开头定义它们:

tax_a = 0.0

P.S。请注意,如果使用浮点数初始化变量并使用浮点常量,则不需要所有float()调用。