29|PYTHON – Functional Taxation

BYU Student Author: @Jae
Reviewers: @MitchFrei, @Jonathan_Weston, @klayton
Estimated Time to Solve: 40 Minutes

We provide the solution to this challenge using:

  • Python

This uses Google Collab as the Integrated Development Environment (IDE). The challenge requires no additional libraries/packages than those native to the python library.

Need a program? Click here.

Overview
It was a Monday morning like any other, and you sat down at your desk, ready to tackle the day’s accounting tasks. Perhaps you would order lunch that day from your favorite restaurant, Little Chicken. But as you logged onto your computer, you noticed a news alert flashing on your screen. “BREAKING NEWS: Tax Brackets Changed Overnight!”

Your heart began to race as you read on. Congress had passed a new tax bill late last night, and the changes were set to take effect immediately. As a junior accountant for a tax preparation company, you wondered how your team would update their tools and stay ahead of the competition.

That’s when your manager appeared at your desk, looking anxious and stressed. “We need a federal income tax calculator in Python, and we need it now!” she said. “With the new tax laws in place, our customers are going to need accurate and reliable calculations more than ever.”

Your mind started racing as you began to think about the coding challenge ahead. You knew that calculating federal income tax was quite simple for your company’s customer-base, but building the calculator in Python was no easy feat. As you rolled up your sleeves and started typing away at your keyboard, you couldn’t help but wonder what other surprises the day might have in store for you. Maybe you would get that lunch after all.

Instructions
Your manager has asked you to build a Federal Income Tax Calculator in Python. In order to build the calculator, you will require the following sections:

  • Determine the appropriate standard deduction and income tax bracket based on filing status using the section of code below
    Starting Code
    def Fed_Income_Tax_Calc(): 
    
     # Determine the appropriate standard deduction and income tax bracket based on filing status 
     filing_status = input('What is your tax filing status? (single | married | head of household) ').lower() 
     if filing_status == 'single': 
         standard_deduction = 12950 
                                         #($min value of tax  bracket, tax rate for bracket) 
         tax_brackets = [(0, 0.1), (10275, 0.12), (41775, 0.22), (89075, 0.24), (170050, 0.32), (215950, 0.35), (539900, 0.37)] 
     elif filing_status == 'head of household': 
         standard_deduction = 19400 
         tax_brackets = [(0, 0.1), (14650, 0.12), (55900, 0.22), (89050, 0.24), (170050, 0.32), (215950, 0.35), (539900, 0.37)] 
     elif filing_status == 'married': 
         filing_status = input('Are you filing with your spouse? (seperately | jointly) ').lower() 
         if filing_status == 'jointly': 
             standard_deduction = 25900 
             tax_brackets = [(0, 0.1), (20550, 0.12), (83550, 0.22), (178150, 0.24), (340100, 0.32), (431900, 0.35), (647850, 0.37)] 
         elif filing_status == 'separately': 
             standard_deduction = 12950 
             tax_brackets = [(0, 0.1), (10275, 0.12), (41775, 0.22), (89075, 0.24), (170050, 0.32), (215950, 0.35), (323925, 0.37)] 
         else: 
             print('Invalid filing status, please try again.\n') 
             Fed_Income_Tax_Calc() 
     else: 
         print('Invalid filing status, please try again.\n') 
         Fed_Income_Tax_Calc() 
    
  • Determine income and deduction type (standard or itemized) and calculate the taxable income by subtracting the deduction
  • Calculate the income tax owed using the tax brackets and corresponding tax rates
  • Output the tax owed

In addition, note the following:

  • The calculator is best built as a function in python
  • Taxable income or taxes owed should not result in a negative value
  • If the user makes a mistake, the function should continue or restart without the need to call it again
    • The function should work regardless of the different ways a user may type an input such as SINGLE/Single/single/Etc
  • The tax brackets are given in (minimum value of individual bracket, tax bracket rate) format as a list of tuples
    • Federal Income Tax brackets can also be viewed here
    • This challenge uses the 2022 brackets
  • Assume that the user knows their total itemized deduction if they select this option
  • Details like filing status, income, and what type of deduction the customer wants can either be collected as arguments/parameters in the function or as inputs by the user within the function code
  • Output can be a returned value or a printed statement from the function
  • Assume the user of the function cannot see your code and will only be inputting what is required to call the function and any other required inputs while the function is running (if applicable)

The following flowchart gives the overall flow of what your calculator is expected to do. The Starting Code found above covers the blue section of the flow chart:

Suggestions and Hints
  • Check figure for single filer with standard deduction and income of $75,000: $9268.00
  • This is a good resource to learn how to create a function in python
  • Be aware of variable types. The default type for an input() function is string
  • if/else conditional statements may be a good way to determine which brackets/deductions to use for each filing status
  • for loops can also help calculate the tax owed if taxable income carries over multiple brackets
  • a list of tuples can generally be referenced in the same way as a list of lists

Solution

Solution Code
def Fed_Income_Tax_Calc(): 
    # Determine the appropriate standard deduction and income tax bracket based on filing status 
    filing_status = input('What is your tax filing status? (single | married | head of household) ').lower() 
    if filing_status == 'single': 
        standard_deduction = 12950 
                                        #($min value of tax  bracket, tax rate for bracket) 
        tax_brackets = [(0, 0.1), (10275, 0.12), (41775, 0.22), (89075, 0.24), (170050, 0.32), (215950, 0.35), (539900, 0.37)] 
    elif filing_status == 'head of household': 
        standard_deduction = 19400 
        tax_brackets = [(0, 0.1), (14650, 0.12), (55900, 0.22), (89050, 0.24), (170050, 0.32), (215950, 0.35), (539900, 0.37)] 
    elif filing_status == 'married': 
        filing_status = input('Are you filing with your spouse? (seperately | jointly) ').lower() 
        if filing_status == 'jointly': 
            standard_deduction = 25900 
            tax_brackets = [(0, 0.1), (20550, 0.12), (83550, 0.22), (178150, 0.24), (340100, 0.32), (431900, 0.35), (647850, 0.37)] 
        elif filing_status == 'separately': 
            standard_deduction = 12950 
            tax_brackets = [(0, 0.1), (10275, 0.12), (41775, 0.22), (89075, 0.24), (170050, 0.32), (215950, 0.35), (323925, 0.37)] 
        else: 
            print('Invalid filing status, please try again.\n') 
            Fed_Income_Tax_Calc() 
    else: 
        print('Invalid filing status, please try again.\n') 
        Fed_Income_Tax_Calc() 
    income = int(input('What was your income for the tax year? ')) 
    # Determine deduction type and calculate the taxable income by subtracting the deduction 
    deduction = input(f'Would you like to itemize or take the standard deduction of ${standard_deduction}? (itemize | standard)') 
    if deduction == 'itemize': 
        deduction = float(input('How much would you like to itemize?')) 
    elif deduction == 'standard': 
        deduction = standard_deduction 
    else: 
        print('Invalid deduction type, please try again.\n') 
        Fed_Income_Tax_Calc() 
    taxable_income = max(0, income - deduction) 
    # Calculate the income tax owed using the tax brackets and corresponding tax rates 
    tax_owed = 0 
    for i in range(len(tax_brackets)): 
        if taxable_income <= tax_brackets[i][0]: 
            break 
        elif i == len(tax_brackets) - 1: 
            tax_owed += (taxable_income - tax_brackets[i][0]) * tax_brackets[i][1] 
        elif taxable_income <= tax_brackets[i+1][0]: 
            tax_owed += (taxable_income - tax_brackets[i][0]) * tax_brackets[i][1] 
        else: 
            tax_owed += (tax_brackets[i+1][0] - tax_brackets[i][0]) * tax_brackets[i][1] 
    # Output the tax owed 
    print(f'Federal Income Taxes Owed: ${tax_owed}') 
Fed_Income_Tax_Calc() 

Solution Video: Challenge 29|PYTHON – Functional Taxation

This challenge was quite interesting to figure out! My solution differs almost entirely from the video solution posted, but I suppose that’s the beauty of challenges like these. I used float datatypes instead of int datatypes which is a negligble difference, but the real difference was the looping method used. Rather than using a combination of if/elif conditionals, I decided to use an enumerate loop and leverage the index variable. The code is deceptively sparse, but efficient.

First, I ensured that the taxable income was greater than the minimum value of the bracket so it would exclude calculations on all irrelevant tax brackets. Then, I used the index variable to see if the tax bracket was an intermediary bracket or the final bracket. If it was an intermediary bracket, it would pull the minimum tax bracket from the next bracket to perform the tax calculation and add it to any existing tax from a prior bracket. If it was the final bracket, I would instead use taxable income for that calculation.

A commented out version of my loop is below:

    # Enter loop to calculate tax amount based on prior inputs
    for index, bracket in enumerate(tax_brackets):
        # Ensuring we ignore brackets outside of the scope of taxable income
        if taxable_income >=  bracket[0]:
            # Condition here to ensure right amount is calculated for each bracket
            if taxable_income > tax_brackets[index+1][0]:
                # Calculate amount owed in lower brackets
                tax = ((tax_brackets[index+1][0] - bracket[0])*bracket[1])+tax
            else:
                # Calculate amount owed in final bracket
                tax = ((taxable_income - bracket[0])*bracket[1])+tax

I utilized the listing of tuples indexing quite a bit to make this work. This was a fun challenge! My solution script along with an example output (using the check figure given) is below. Happy coding!

This is a cool challenge. I definitely spent a lot of time getting the tax brackets into the function haha. But I think this was a great challenge to practice “user-proofing” my code. Something that could be included next time is to find out if the user has any tax credits that they can apply towards their taxes owed.

Here's My Solution
def tax_calculator():
    # Get the status
    status_list = ['s','mfj','mfs','hoh']
    status_list_full = ['Single','Married Filing Jointly','Married Filing Separately','Head of Household']
    standard_deduction_list = [12950,25900,12950,19400]
    keep_running = True
    while keep_running:
        status = input("Welcome User, how will you be filing? Type the acronym that follows your filing type.\nSingle (S)\nMarried Filing Jointly (MJF)\nMarried Filing Separately (MFS)\nHead of Household (HOH)\n")
        status = status[0].lower()
        if status in status_list:
            i = status_list.index(status)
            stan_amt = standard_deduction_list[i]
            print(f"Your filing status is: {status_list_full[i]}.")
            keep_running = False
        else:
            print('\nThat is not a valid filing status.\n')
            continue

    # Get the Deduction type and amount
    keep_running = True
    while keep_running:
        deduction = input("Do you want to take the STANDARD or ITEMIZED deductions from you income?\n")
        if deduction[0].lower() == 's':
            deduction = 's'
            print(f"Your deduction type is: Standard.\n")
            keep_running = False
        elif deduction[0].lower() == 'i':
            deduction = 'i'
            while True:
                try:
                    item_amt = float(input(f"Your deduction type is: Itemized.\nHow much is your itemized deduction?:\t"))
                    item_amt = abs(item_amt)
                    print(f"Your itemized deduction amount is: {item_amt}\n")
                    break
                except:
                    pass
                print("\nThat is not a valid deduction amount.\n")
            keep_running=False
        else:
            print("\nThat is not a valid deduction type.")
            continue     


    # Get the income
    while True:
        try:
            income = float(input("Please enter your taxable income:\t"))
            if income >= 0:
                print(f"Your taxable income is: {income}\n")
                break
        except:
            pass
        print("\nIncome should not be negative or a text object\n")



    # Use the deduction
    if deduction == 's':
        income = income - stan_amt
    elif deduction == 'i':
        income = income - item_amt


    # Get Tax Bracket
    if status == 's':
        if income < 10275:
            tax = income * .1
        elif income > 10276 and income < 41775:
            tax = 1027.5 + .12*(income-10275)
        elif income > 41779 and income < 89075:
            tax = 4807.5 + .22*(income-41775)
        elif income > 89076 and income < 170050:
            tax = 15213.5 + .24*(income-89075)
        elif income > 170051 and income < 215950:
            tax = 34647.5 + .32*(income-170050)
        elif income > 215951 and income < 539900:
            tax = 49335.5 + .35*(income-215950)
        elif income > 539901:
            tax = 162718 + .37*(income-539900)

    elif status == 'mfj':
        if income < 20550:
            tax = income * .1
        elif income > 20551 and income < 83550:
            tax = 2055 + .12*(income-20550)
        elif income > 83551 and income < 178150:
            tax = 9615 + .22*(income-83550)
        elif income > 178151 and income < 340100:
            tax = 30427 + .24*(income-178150)
        elif income > 340101 and income < 431900:
            tax = 69295 + .32*(income-340100)
        elif income > 431901 and income < 647850:
            tax = 98671 + .35*(income-431900)
        elif income > 647851:
            tax = 174253.5 + .37*(income-647850)

    elif status == 'mfs':
        if income < 10275:
            tax = income * .1
        elif income > 10276 and income < 41775:
            tax = 1027.5 + .12*(income-10275)
        elif income > 41779 and income < 89075:
            tax = 4807.5 + .22*(income-41775)
        elif income > 89076 and income < 170050:
            tax = 15213.5 + .24*(income-89075)
        elif income > 170051 and income < 215950:
            tax = 34647.5 + .32*(income-170050)
        elif income > 215951 and income < 539900:
            tax = 49335.5 + .35*(income-215950)
        elif income > 539901:
            tax = 162718 + .37*(income-539900)

    elif status == 'hoh':
        if income < 14650:
            tax = income * .1
        elif income > 14651 and income < 55900:
            tax = 1465 + .12*(income-14650)
        elif income > 55901 and income < 89050:
            tax = 6415 + .22*(income-55900)
        elif income > 89051 and income < 170050:
            tax = 13708 + .24*(income-89050)
        elif income > 170051 and income < 215950:
            tax = 33148 + .32*(income-170050)
        elif income > 215951 and income < 539900:
            tax = 47836 + .35*(income-215950)
        elif income > 539901:
            tax = 161218.5 + .37*(income-539900)


    print(f"Your filing status is: {status_list_full[i]}.")
    if deduction == 's':
        print(f"Your deduction type is: Standard.")
        print(f"Your Standard Deduction amount is: {standard_deduction_list[i]}")
    elif deduction == 'i':
        print(f"Your deduction type is: Itemized.")
        print(f"Your itemized deduction amount is: {item_amt}")
    print(f"Your taxable income after deductions is: {income}")
    print(f"Your tax expense is: {tax}")


tax_calculator()

I went at this one recursively because the input size (the list of tax brackets) is a fixed length. The recursive function calculates the tax liability for the current bracket and then calls itself with taxable income decreased by the amount taxed in that bracket and the list of taxable incomes with the taxed bracket removed.

In any function call, if the income is less than the range of the current bracket, we can return the income times the current rate. If we get to the end of the list of brackets, we know we are in the highest bracket, so we can also return the income times the current rate. Otherwise, we calculate tax for the entire bracket range and make the recursive call.

def main():
    filing_status = get_filing_status()
    tax_brackets = get_tax_brackets(filing_status)
    taxable_income = get_taxable_income(get_income(), get_deduction(filing_status))

    print(f'Total tax is ${calculate_tax(taxable_income, tax_brackets)}')

def calculate_tax(income, tax_brackets):
    if len(tax_brackets) == 1:
        return income * tax_brackets[0][1]
    elif income < tax_brackets[1][0] - tax_brackets[0][0]:
        return income * tax_brackets[0][1]
    tax = (tax_brackets[1][0] - tax_brackets[0][0]) * tax_brackets[0][1]
    return tax + calculate_tax(income - (tax_brackets[1][0] - tax_brackets[0][0]), tax_brackets[1:])

def validate_type(input, func):
    try:
        return int(input)
    except:
        print('Invalid input type. Please try again.\n')
        return func()

def get_filing_status():
    status = input('What is your tax filing status? (single | head of household | married filing separately | married filing jointly) ').lower() 
    valid_statuses = ['single', 'head of household', 'married filing separately', 'married filing jointly']
    if status in valid_statuses:
        return status
    print('Invalid filing status. Please try again.\n')
    return get_filing_status()

def get_income():
    return validate_type(input('What is your total income for the tax year? '), get_income)

def get_standard_deduction(filing_status):
    if filing_status == 'single': 
        standard_deduction = 12950 
    elif filing_status == 'head of household': 
        standard_deduction = 19400 
    elif filing_status == 'married filing separately': 
        standard_deduction = 12950
    elif filing_status == 'married filing jointly': 
        standard_deduction = 25900 
    return standard_deduction

def get_itemized_deduction():
    will_itemize = input('Do you plan on itemizing your deductions? (y | n) ').lower()
    if will_itemize == 'y':
        return validate_type(input('What is your total itemized deduction? '), get_itemized_deduction)
    elif will_itemize == 'n':
        return 0
    else:
        print('Invalid input. Please try again.\n')
        return get_itemized_deduction()

def get_deduction(filing_status):
    return max(get_standard_deduction(filing_status), get_itemized_deduction())

def get_taxable_income(income, deduction):
    return max(income - deduction, 0)

def get_tax_brackets(filing_status):
    if filing_status == 'single': 
        tax_brackets = [(0, 0.1), (10275, 0.12), (41775, 0.22), (89075, 0.24), (170050, 0.32), (215950, 0.35), (539900, 0.37)] 
    elif filing_status == 'head of household': 
        tax_brackets = [(0, 0.1), (14650, 0.12), (55900, 0.22), (89050, 0.24), (170050, 0.32), (215950, 0.35), (539900, 0.37)] 
    elif filing_status == 'married filing separately': 
        tax_brackets = [(0, 0.1), (10275, 0.12), (41775, 0.22), (89075, 0.24), (170050, 0.32), (215950, 0.35), (323925, 0.37)] 
    elif filing_status == 'married filing jointly': 
        tax_brackets = [(0, 0.1), (20550, 0.12), (83550, 0.22), (178150, 0.24), (340100, 0.32), (431900, 0.35), (647850, 0.37)] 
    else: 
        print('Invalid filing status, please try again.\n') 
        return get_filing_status()
    return tax_brackets

if __name__ == '__main__':
    main()
2 Likes

my solution

def federal_income_tax_calculator():
# Define tax brackets for 2022
tax_brackets = [
(0, 0.1),
(9950, 0.12),
(40525, 0.22),
(86375, 0.24),
(164925, 0.32),
(209425, 0.35),
(523600, 0.37)
]

# Get user inputs for filing status, income, and deduction type
while True:
    # Get filing status and ensure it's in the correct format
    filing_status = input("Enter your filing status (Single, Married, Head of Household): ").strip().lower()
    if filing_status not in ["single", "married", "head of household"]:
        print("Invalid filing status. Please enter Single, Married, or Head of Household.")
        continue

    # Get income and ensure it's a positive number
    income = input("Enter your total income: ")
    if not income.isdigit() or int(income) < 0:
        print("Invalid income amount. Please enter a positive number.")
        continue
    income = int(income)

    # Get deduction type and ensure it's in the correct format
    deduction_type = input("Do you want to use the standard deduction or itemized deduction? ").strip().lower()
    if deduction_type not in ["standard", "itemized"]:
        print("Invalid deduction type. Please choose between Standard and Itemized deduction.")
        continue

    # Calculate the standard deduction based on filing status
    if filing_status == "single":
        standard_deduction = 12550
    elif filing_status == "married":
        standard_deduction = 25100
    else:
        standard_deduction = 18800

    # Calculate taxable income based on the deduction type
    if deduction_type == "standard":
        taxable_income = max(0, income - standard_deduction)
    else:
        itemized_deduction = input("Enter your total itemized deduction: ")
        if not itemized_deduction.isdigit() or int(itemized_deduction) < 0:
            print("Invalid itemized deduction amount. Please enter a positive number.")
            continue
        itemized_deduction = int(itemized_deduction)
        taxable_income = max(0, income - itemized_deduction)

    # Calculate income tax based on tax brackets
    income_tax = 0
    remaining_income = taxable_income
    for min_income, tax_rate in tax_brackets:
        if remaining_income <= 0:
            break
        if remaining_income <= min_income:
            income_tax += remaining_income * tax_rate
            break
        else:
            income_tax += min_income * tax_rate
            remaining_income -= min_income

    # Output the calculated income tax
    print(f"Your federal income tax owed is: ${income_tax:.2f}")
    break

Call the function to run the tax calculator

federal_income_tax_calculator()

1 Like