累进税百分比计算的Elif和范围函数

2024-06-01 10:28:06 发布

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

我正在创建一个程序,用户将年收入作为输入,所得税税率将根据百分比阈值进行调整(参见本文末尾的图片,了解收入范围与百分比阈值)。例如,10万欧元收入的50%将从超过60001欧元的收入中支付(如下表所示)。40%在45000-60000之间,20%在15000-30000之间,10%在0-10000之间。等式应该是0.5*40000+0.4*15000+0.3*15000+0.2*15000+0.1*10000=35000

输出应该类似于: 给你的年收入:100000你纳税35000.0欧元。你们的税率是:35.0%。 给你的年收入:54000你纳税12600.0欧元。你们的税率是:23.3332%

这就是我尝试过的:

yearly = int(input("Tell your yearly income:"))
one = 0.1
two = 0.2
three = 0.3
four = 0.4
five = 0.5 
if yearly in range(1,15000):
    print("You pay taxes in total:",yearly*one)
if yearly in range(15001,30000):
    print("You pay taxes in total:",yearly*two)
if yearly in range(30001,45000):
    print("You pay taxes in total:",yearly*three)
if yearly in range(45001,60000):
    print("You pay taxes in total:",yearly*four)
if yearly > 60000:
    print("You pay taxes in total:",yearly*five)

税收比例不像我希望的那样大。我假设这应该通过elif和range函数来实现。也许百分比的最小值和最大值会有帮助,但我不知道如何将输出转化为百分比。请注意,我可能在这里有一些理解问题,数学不是我最擅长的游戏,但我尽了最大的努力来描述这个问题

这是一张收入统计表与使用的税收百分比。 Income vs. taxation percentage


Tags: inyouifrange阈值onepaytotal
1条回答
网友
1楼 · 发布于 2024-06-01 10:28:06

优化方式:

下面是一种更优化的方法(有关枚举的非优化方法,请参见底部)。我将百分比和阈值存储在列表中,并且taxes在循环期间递增:

yearly = int(input("Tell your yearly income:"))

percents = [0.1, 0.2, 0.3, 0.4, 0.5]
thresholds = [0, 15000, 30000, 45000, 60000]

taxes = 0
for i in range(len(percents)):
    if i == len(thresholds) - 1 or yearly < thresholds[i+1]:
        taxes += (yearly - thresholds[i]) * percents[i]
        break
    else:
        taxes += (thresholds[i+1] - thresholds[i]) * percents[i]

print("You pay {} taxes".format(taxes))
print("Your taxation percent is: {}%".format(taxes/yearly*100))

产出的例子:

# Test 1
Tell your yearly income:100000
You pay 35000.0 taxes
Your taxation percent is: 35.0%

# Test 2
Tell your yearly income:54000
You pay 12600.0 taxes
Your taxation percent is: 23.333333333333332%

非优化方式:

这里的关键是要有一个变量temp(用temp = yearly初始化),当您应用税收时,该变量会减少:

yearly = int(input("Tell your yearly income:"))

one = 0.1
two = 0.2
three = 0.3
four = 0.4
five = 0.5

diff = 15000

temp = yearly
taxes = 0
if yearly in range(1,15000):
    taxes += temp * one
else:
    taxes += diff * one
    temp -= diff
if yearly in range(15001,30000):
    taxes += temp * two
else:
    taxes += diff * two
    temp -= diff
if yearly in range(30001,45000):
    taxes += temp * three
else:
    taxes += diff * three
    temp -= diff
if yearly in range(45001,60000):
    taxes += temp * four
else:
    taxes += diff * four
    temp -= diff
if yearly > 60000:
    taxes += temp * five

print("You pay {} taxes".format(taxes))
print("Your taxation percent is: {}%".format(taxes/yearly*100))

相关问题 更多 >