income tax calculation python

user3014014 picture user3014014 · Nov 21, 2013 · Viewed 24k times · Source

How do I go about making a for-loop with a range 70000 and above? I'm doing a for-loop for an income tax and when income is above 70000 there is a tax of 30%. Would i do something like for income in range(income-70000)?

Well, at first i developed a code that didn't use a loop and it worked just fine, but then i was notified that i needed to incorporate a loop in my code. This is what i have, but it just doesn't make sense for me to use a for loop. Can someone help me?

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)

Okay, so I have now tried with a while loop, but it doesn't return a value. Tell me what you think. I need to calculate the income tax based on an income. first 10000 dollars there is no tax. next 20000 there is 10%. Next 40000 there is 20%. and above 70000 is 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

Answer

Raymond Hettinger picture Raymond Hettinger · Nov 21, 2013

Q: How do I go about making a for-loop with a range 70000 and above?

A: Use the itertools.count() method:

import itertools

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

Q: I need to calculate the income tax based on an income. first 10000 dollars there is no tax. next 20000 there is 10%. Next 40000 there is 20%. and above 70000 is 30%.

A: The bisect module is great for doing lookups in ranges:

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