Home > OS >  I need help writing a code for this question
I need help writing a code for this question

Time:07-22

Im using pycharm

Write a program that will calculate tax on the user's annual salary. It must : 1. ask the user to enter their name, 2. ask the user to enter their annual salary 3. print their tax bill on screen

However, Australian tax laws are complicated.

They follow these rules:

•0 – $18,200 Nil ($0 tax paid)

•$18,201 – $45,000 19 cents for each $1 over $18,200

•$45,001 – $120,000 $5,092 plus 32.5 cents for each $1 over $45,000

•$120,001 – $180,000 $29,467 plus 37 cents for each $1 over $120,000

•$180,001 and over, $51,667 plus 45 cents for each $1 over $180,000

CodePudding user response:

This function works and does not require any dependencies to work.

def taxesDue(x:float):
    '''Function that takes in a person's yearly salary (unit: AUD) and returns the taxes due (unit: AUD)'''
    if(x <= 18200):
        return 0                         # lucky person
    elif(x <= 45000):
        return round(0.19*(x-18200), 2)
    elif(x<= 120000):
        return round(5092 0.325*(x-45000), 2)
    elif(x <= 180000):
        return round(29467 0.37*(x-120000),2)
    else:
        return round(51667 0.45*(x-180000)*0.45, 2)

The sample output is

taxesDue(16500)
>0 

taxesDue(18201)
>0.19

taxesDue(1e6) # scientific notation for 1 million (float)
>217717.0

Since all of us were new to coding at one point. Some explanation on things you will likely encounter on your journey deeper into Python.

  1. The function's input is the salary in AUD (can be an integer like 20000 or a float such as 20000.95 where the decimals represent cents. Therefore, I rounded the taxes due to two digits through round(y, 2). In case the input salary is always of type int you can leave the rounding out as the output will naturally only have two decimals.

  2. Speaking of float and int. Types in Python are dynamic so the float:x in the function's argument list is syntactic sugar (nice to look at for the developer/user but no impact on the rest of the code) to emphasize that a floating point number (the salary) goes in rather than a string str like x=Hello IRS. Note that int is a subset of float so float is more general.

  3. The if/elif/else iterates through the conditions (e.g. x <= 45000). elif and the final else is only checked if none of the previous conditions was met. Note that this naturally reflects your task at hand.

  4. Any function is exited as soon as any of the return's is reached.

  5. Comments such as #lucky or the the comment right underneath the function's head '''Function... will go into the docstring. In turn, the developer can retrieve it when running

?taxesDue

enter image description here

If you need to print the result run

x = 475000       # or whatever salary you can think of
print(taxesDue(x))
  • Related