所得税计算python

use*_*014 3 python iteration for-loop bisection

如何制作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)
Run Code Online (Sandbox Code Playgroud)

好的,所以我现在尝试使用while循环,但它没有返回值.告诉我你的想法.我需要根据收入计算所得税.先10000美元没有税.接下来的20000有10%.接下来40000有20%.超过70000是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
Run Code Online (Sandbox Code Playgroud)

Ray*_*ger 13

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

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

import itertools

for amount in itertools.count(70000):
    print(amount * 0.30)
Run Code Online (Sandbox Code Playgroud)

问:我需要根据收入计算所得税.先10000美元没有税.接下来的20000有10%.接下来40000有20%.超过70000是30%.

答:对开模块是非常适合在范围查找做:

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
Run Code Online (Sandbox Code Playgroud)