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

2024-05-16 01:15:28 发布

您现在位置: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))

Tags: 用户目的formatinputyouriffloattotal
3条回答

只有当某些条件为真时,才定义tax_atax_btax_ctax_s。如果条件不为true,则不定义变量

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

if income < 35000:
    tax_a = float((income * 0.15))
else:
    tax_a = 0.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

另请注意,如果您以浮点开始初始化变量并使用浮点常量,则所有float()调用都是不必要的

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

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

相关问题 更多 >