所得税计算python

2024-04-27 03:01:02 发布

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

如何在70000及以上的范围内进行for循环?我正在为所得税做一个循环,当收入超过70000时,就要交30%的税。我能做些像for income in range(income-70000)这样的事情吗?

嗯,一开始我开发了一个不使用循环的代码,它运行得很好,但后来我接到通知,我需要在代码中包含一个循环。这就是我所拥有的,但对我来说使用for循环是没有意义的。有人能帮我吗?

def tax(income):

for income in range(10001):
    tax = 0
    for income in range(10002,30001):
        tax = income*(0.1) + tax
        for income in range(30002,70001):
            tax = income*(0.2) + tax
            for income in range(70002,100000):
                tax = income*(0.3) + tax
print (tax)

好的,我现在尝试了一个while循环,但是它没有返回值。告诉我你的想法。我需要根据收入计算所得税。头一万美元不用交税。接下来的2万是10%。接下来的40000有20%。7万以上的占30%。

def taxes(income):

income >= 0
while True:
    if income < 10000:
        tax = 0
    elif income > 10000 and income <= 30000:
        tax = (income-10000)*(0.1)
    elif income > 30000 and income <= 70000:
        tax = (income-30000)*(0.2) + 2000
    elif income > 70000:
        tax = (income - 70000)*(0.3) + 10000
return tax

Tags: and代码infordefrange事情意义
3条回答

两个函数都不能计算所需的值。你需要这样的东西:

import sys

income = 100000
taxes = [(10000, 0), (20000, 0.1), (40000, 0.2), (sys.maxint, 0.3)]

billed_tax = 0
for amount, tax in taxes:
    billed_amount = min(income, amount)
    billed_tax += billed_amount*tax
    income -= billed_amount
    if income <= 0: 
        break

>>> billed_tax
19000.0

问:如何制作70000及以上范围的for循环?

A:使用itertools.count()方法:

import itertools

for amount in itertools.count(70000):
    print(amount * 0.30)

问:我需要根据收入计算所得税。头一万美元不用交税。接下来的2万是10%。接下来的40000有20%。70000以上占30%。

A:bisect module非常适合在以下范围内进行查找:

from bisect import bisect

rates = [0, 10, 20, 30]   # 10%  20%  30%

brackets = [10000,        # first 10,000
            30000,        # next  20,000
            70000]        # next  40,000

base_tax = [0,            # 10,000 * 0%
            2000,         # 20,000 * 10%
            10000]        # 40,000 * 20% + 2,000

def tax(income):
    i = bisect(brackets, income)
    if not i:
        return 0
    rate = rates[i]
    bracket = brackets[i-1]
    income_in_bracket = income - bracket
    tax_in_bracket = income_in_bracket * rate / 100
    total_tax = base_tax[i-1] + tax_in_bracket
    return total_tax

如果您真的必须循环,一种方法是分别计算每个收入单位的税收:

def calculate_tax(income):
    tax = 0
    brackets = {(10000,30000):0.1, ...}
    for bracket in brackets:
        if income > bracket[0]:
            for _ in range(bracket[0], min(income, bracket[1])):
                tax += brackets[bracket]
    return tax

相关问题 更多 >