Python raw input function for tax calculation - python

I am trying to make a simple calculator for working out the tax due on a salary. Please see the code below:
I keep getting this error and I don't know what is wrong, please help :) thanks!
Traceback (most recent call last):
File "python", line 13
elif salary > 11000 and salary < 43000:
^
SyntaxError: invalid syntax
CODE:
salary = raw_input ("What is your salary?")
print "So your gross annual salary is %r GBP" % (salary)
print "\nNow we need to calculate what your net salary is."
def taxes(salary):
salary >= 0
while true:
if salary < 11000:
tax = 0
elif salary > 11000 and salary < 43000:
tax = (0.2 * income) - 2200
elif salary > 43000 and salary < 150000:
tax = (0.4 * (salary - 43000)) + 6400
elif salary > 150000:
tax = ((salary - 150000) * 0.45) + 6400 + 42800
return tax

Steps to correct your code
step1 : the salary data type should be of int, to correct..use the following code
step 2: Indentation is compulsory in python, so indent your code very well
step 3: Add an else statement after the conditional statements
step 4: indent return statement
change your code to this one
salary = int(raw_input ("What is your salary?"))
print "So your gross annual salary is %r GBP" % (salary)
print "\nNow we need to calculate what your net salary is."
def taxes(salary):
salary >= 0
while true:
if salary < 11000:
tax = 0
elif salary > 11000 and salary < 43000:
tax = (0.2 * income) - 2200
elif salary > 43000 and salary < 150000:
tax = (0.4 * (salary - 43000)) + 6400
elif salary > 150000:
tax = ((salary - 150000) * 0.45) + 6400 + 42800
else :
tax = undefined
return tax

It felt like there was a better way of doing this, so I came up with an alternative route:
tax_bands = [11000, 43000, 150000]
tax_amts = [0.2, 0.4, 0.45]
salary = 43001
Placing the thresholds and amounts into a list means that you can change them more easily if you need to.
The function below creates a list of the tax calculations, tax_list, and then a separate list of the maximum tax liability in each band called max_tax (the upper band has no maximum).
It then compares the values in the lists, and overwrites the tax_list if the corresponding value is larger than the maximum.
Then it calculates the sum of all values in tax_list greater than zero and returns it.
def taxes(salary, tax_bands, tax_amts):
tax_list = [(pct * (salary - band)) for (band, pct) in zip(tax_bands, tax_amts)]
max_tax = []
for index, sal in enumerate(tax_bands[:-1]):
max_tax.append(tax_bands[index + 1] - sal)
max_tax = [segment * tax for segment, tax in zip(max_tax, tax_amts[:-1])]
for index, value in enumerate(tax_list):
try:
if value > max_tax[index]:
tax_list[index] = max_tax[index]
except:
pass
tax_to_pay = sum([x for x in tax_list if x > 0])
return tax_to_pay
print taxes(salary, tax_bands, tax_amts)
salary = input ("What is your salary?")
print "So your gross annual salary is %r GBP" % (salary)
print "\nYour net annual salary is: {} GBP".format(salary - taxes(salary, tax_bands, tax_amts))
To be super safe, you could also have the first line in the function call int(salary) using a try except just to check that it's the right type and that someone hasn't entered 43,000.

That because there are indent error in line number 12, now you can just copy pust this :
note : salary > 11000 and salary < 43000 equivalent to 11000 < salary < 43000 in python:
salary = raw_input ("What is your salary?")
print "So your gross annual salary is %r GBP" % (salary)
print "\nNow we need to calculate what your net salary is."
def taxes(salary):
while true:
if salary < 11000:
tax = 0
elif 11000 < salary < 43000:
tax = (0.2 * income) - 2200
elif salary > 43000 and salary < 150000:
tax = (0.4 * (salary - 43000)) + 6400
elif salary > 150000:
tax = ((salary - 150000) * 0.45) + 6400 + 42800
return tax

As the comments have already stated, your indentation is incorrect. See below:
def taxes(salary):
salary >= 0
tax = 0
if salary < 11000:
tax = 0
elif salary > 11000 and salary < 43000:
tax = (0.2 * income) - 2200
elif salary > 43000 and salary < 150000:
tax = (0.4 * (salary - 43000)) + 6400
elif salary > 150000:
tax = ((salary - 150000) * 0.45) + 6400 + 42800
print("Value of tax is: " + str(tax))
return tax
salary = raw_input ("What is your salary?")
print "So your gross annual salary is %r GBP" % (salary)
print "\nNow we need to calculate what your net salary is."
print("\nHere is your net salary after taxes: %r" % (taxes(int(salary))))
With python, indentations are how you tell the interpreter which blocks of code fall where (unlike with Java for example with semicolons being the end of line delimiter). By not indenting properly on your elif statements, you are essentially telling the program there is an elif without an if hence your syntax problem.

Related

change after purchase not giving the right breakdown

def main():
money1 = input("Purchase price: ")
money2 = input("Paid amount of money: ")
price = int(money1)
paid = int(money2)
change = paid - price
ten_euro = change // 10
five_euro = change % 10 // 5
two_euro = change % 5 // 2
one_euro = (change % 2)
if price < paid:
print("Offer change:")
if change >= 10:
print(ten_euro, "ten-euro notes")
if (change % 10) >= 5:
print(five_euro, "five-euro notes")
if (change % 5) >= 2:
print(two_euro, "two-euro coins")
if (change % 2) >= 2:
print(one_euro, "one-euro coins")
else:
print("No change")
if __name__ == "__main__":
main()
Create a program that asks how much purchases cost and the amount of paid money and then prints the amount of change. Simplify the program by only allowing the use of sums of 1, 2, 5, and 10 euros. Ensure that the total price is always in full euros.
My problem is with the one-euro coins, as it is not showing as expected.
Examples of how the program should work:
Purchase price: 12
Paid amount of money: 50
Offer change:
3 ten-euro notes
1 five-euro notes
1 two-euro coins
1 one-euro coins
Purchase price: 9
Paid amount of money: 20
Offer change:
1 ten-euro notes
1 one-euro coins
This line is incorrect: if (change % 2) >= 2.
This can never be true. You probably meant: if (change % 2) >= 1.
Apart from that I think you could simplify the program by decrementing the change variable as you calculate the different denominations. You can use the builtin method divmod for this.
You can also check if the ten_euro, five_euro, etc are greater than zero in the printout rather than re-calculating their amount.
ten_euro, change = divmod(change, 10)
five_euro, change = divmod(change, 5)
two_euro, change = divmod(change, 2)
one_euro = change
if price < paid:
print("Offer change:")
if ten_euro:
print(ten_euro, "ten-euro notes")
if five_euro:
print(five_euro, "five-euro notes")
if two_euro:
print(two_euro, "two-euro coins")
if one_euro:
print(one_euro, "one-euro coins")
else:
print("No change")
We got to calculate # one_euro count better and you are there.
Here is a working solution, included a check on the total change aswell.
def main():
money1 = input("Purchase price: ")
money2 = input("Paid amount of money: ")
price = int(money1)
paid = int(money2)
change = paid - price
ten_euro_count = change // 10
five_euro_count = change % 10 // 5
two_euro_count = change % 5 // 2
sum_of_change = 0
if price < paid:
print("Offer change:")
if change >= 10:
print(ten_euro_count, "ten-euro notes")
sum_of_change = sum_of_change + ten_euro_count * 10
if (change % 10) >= 5:
print(five_euro_count, "five-euro notes")
sum_of_change = sum_of_change + five_euro_count * 5
if (change % 5) >= 2:
print(two_euro_count, "two-euro coins")
sum_of_change = sum_of_change + two_euro_count * 2
if change - sum_of_change != 0:
one_euro_count = 1
print(one_euro_count, "one-euro coins")
else:
print("No change")
if __name__ == "__main__":
main()
Faulty decision structure;
if (change % 2) >= 2
Code change;
def main():
money1 = int(input("Purchase price: "))
money2 = int(input("Paid amount of money: "))
change = money2 - money1
ten_euro = change // 10
five_euro = (change % 10) // 5
two_euro = (change % 5) // 2
total = 0
if money1 < money2:
print("Offer change:")
if change >= 10:
print(ten_euro, "ten-euro notes")
total += ten_euro*10
if (change % 10) >= 5:
print(five_euro, "five-euro notes")
total += five_euro*5
if (change % 5) >= 2:
print(two_euro, "two-euro coins")
total += two_euro*2
if change - total > 0:
print(change-total, "one-euro coins")
else:
print("No change")
if __name__ == "__main__":
main()

name is not defined i have already defined the name

PFB the below code I am trying to calculate tax. why do I get the NameError: name 'tax' is not defined.
I have defined tax below still it throws the error tax not defined.
hw = float(input("Please enter total hours worked"))
hp = float(input("Please enter the hourly rate"))
# Pay and OT Calculations
rp = hp * hw
if hw == 40 or hw <40 :
ot = 0
tp = rp + ot
elif hw > 40 and hw <50 :
ot = (hw-40)*(hp*1.5)
tp = rp + ot
elif hw > 50 and hw < 60 :
ot = (hw-40)*(hp*2)
tp = rp + ot
elif hw > 60 or hw == 60 :
ot = (hw-40)*(hp*2.5)
tp = rp + ot
else :
print ("Thanks")
# tax Calculations
if tp == 200 :
tax = float((tp/100)*15)
elif tp > 200 and tp < 300 :
tax = ((tp-200)/100*20) + ((200/100)*15)
elif tp >300 and tp < 400 :
tax = ((tp-300)/100*25) + (((tp-200)-(tp-300))/100*20) + ((200/100)*15)
elif tp >400 and tp == 400 :
tax = ((tp-400)/100*30) + (((tp-200)-(tp-300)-(tp-400))/100*25) + (((tp-200)-(tp-300)/100)*20) + ((200/100)*15)
else :
print ("Thanks")
# Printing Results
print ("Your Salary has been credited")
print ("Regular Pay = ", rp)
print ("Overtime =", ot)
print ("Gross Salary before tax deductions = ", tp)
print ("Income Tax applicable =", tax)
you are using your variables across the entire function but are only defining them in the if/else cases. This adds a lot of room for error of missing a definition somewhere within a case as in
...
if tp == 200 :
tax = float((tp/100)*15)
elif tp > 200 and tp < 300 :
tax = ((tp-200)/100*20) + ((200/100)*15)
elif tp >300 and tp < 400 :
tax = ((tp-300)/100*25) + (((tp-200)-(tp-300))/100*20) + ((200/100)*15)
elif tp >400 and tp == 400 :
tax = ((tp-400)/100*30) + (((tp-200)-(tp-300)-(tp-400))/100*25) + (((tp-200)-(tp-300)/100)*20) + ((200/100)*15)
else :
# NO tax defined here
print ("Thanks")
...
You should define the function-scope variables on the top of your function as:
hw = float(input("Please enter total hours worked"))
hp = float(input("Please enter the hourly rate"))
rp = 0
ot = 0
tp = 0
tax = 0
# Pay and OT Calculations
...
# Printing Results
print ("Your Salary has been credited")
print ("Regular Pay = ", rp)
print ("Overtime =", ot)
print ("Gross Salary before tax deductions = ", tp)
print ("Income Tax applicable =", tax)
By setting these default values you are sure to never miss the variable initialization in your code and you will not need to add extra logic to handle the tax variable in the edge cases where it should not be changed (the else case in your question.

Why can't my tax_a,b,c be found?

The purpose is to get the income from the user and apply a set of taxes based on the amount of money the user earns.
income = float(input('Enter your income: $ '))
if income < 35000:
tax_a = float((income * 0.15))
if (income - 35000) < 100000:
tax_b = float((income * 0.25))
if (income - 100000) > 100000:
tax_c = float((income * 0.35))
if income > 50000:
tax_s = (income * 0.05)
fed_tax = float((tax_a + tax_b + tax_c))
total_tax = (fed_tax + tax_s)
print('Your total tax liability is: ${:.2f}'.format(total_tax))
print('[details Federal tax: {:.2f}, State tax: {:.2f}'.format(fed_tax, tax_s))
You are only defining tax_a, tax_b, tax_c and tax_s if some condition is true. If the condition is not true, you leave the variable undefined.
I'm not a tax lawyer, but I assume the tax in a given category is 0 if the condition does not apply:
if income < 35000:
tax_a = float((income * 0.15))
else:
tax_a = 0.0
...and so on.
Need to initialize your variables and learn about "variable scope".
tax_a = tax_b = tax_c = tax_s = 0
income = float(input('Enter your income: $ '))
# ...
$ python incometax.py
Enter your income: $ 100000
Traceback (most recent call last):
File "incometax.py", line 15, in <module>
fed_tax = float((tax_a + tax_b + tax_c))
NameError: name 'tax_a' is not defined
The problem is that tax_a is only defined when a certain condition occurs. Since you always need these variables in the final calculation, you should define them at the beginning of your program:
tax_a = 0.0
p.s. Note that all of the float() calls are unnecessary if you initialize variables with floats to begin with and use floating point constants.

MIT opencourseware - stuck on a basic issue, credit card minimum payment over a year calculation

Basically I'm pretty stuck on this issue, I've linked the question below, it's part 'b' I'm stuck on, or the second question in the document:
http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-00sc-introduction-to-computer-science-and-programming-spring-2011/unit-1/lecture-4-machine-interpretation-of-a-program/MIT6_00SCS11_ps1.pdf
If I'm honest it's just got to the point where I'm totally confused! I've put my code below:
balance = float(raw_input('Vot is the outstanding balance? '))
InrAn = float(raw_input('Vot is the annual interest rate as a decimal? '))
month = 1
monthPay = 10
monthInr = InrAn/12.0
newBalance = balance
while balance > 0:
newBalance = newBalance * (1 + monthInr) - monthPay
month +=1
if month > 12:
month = 1
newBalance = balance
monthPay += 10
This does essentially nothing, I know, and it's not yet complete. If I add a 'print month' statement it just seems to show that the code just goes up to 12, then starts at 1 again. Any tips/prods in the right direction?
monthly_payment = 10.0
while True:
current_balance = start_balance
for month in range(1, 13):
current_balance = current_balance * (1. + monthly_rate) - monthly_payment
current_balance = round(current_balance, 2)
if current_balance <= 0.0:
break
if current_balance <= 0.0:
print("RESULT")
print("Monthly payment to pay off debt in 1 year: {}".format(int(monthly_payment)))
print("Number of months needed: {}".format(month))
print("Balance: {:0.2f}".format(current_balance))
break
monthly_payment += 10.0

Not getting right output...logic correct

My code is giving right results except for balance=3926. Lowest Payment: 370 whereas it should be 360.The program should print lowest monthly payment for given annual interest rate .Given an initial balance, code should compute the balance at the end of the year. we are trying our initial balance with a monthly payment of $10. If there is a balance remaining at the end of the year, we write code that would reset the balance to the initial balance, increase the payment by $10, and try again (using the same code!) to compute the balance at the end of the year, to see if this new payment value is large enough
annualInterestRate = 0.2
balance = 3926
monthlyinterestrate = annualInterestRate/12.0
remainingBalance = balance
month = 1
total = 0
payment = 10
def CheckMinimumPayment(payment,balance):
"Checking if payment is in correct balance"
while(payment*12 < balance):
payment += 10
return payment
payment = CheckMinimumPayment(payment,balance)
while(month <= 12):
remainingBalance = remainingBalance - payment + (annualInterestRate / 12.0) * (remainingBalance - payment)
month += 1
total += payment
payment = CheckMinimumPayment(payment,total+remainingBalance)
print("Lowest Payment: " + str(payment))
The problem is that you're not re-iterating through the interest loop (what you have as while(month <= 12)) each time you try a new payment. Write that loop into a function, and call it each time you try a new payment. The total owed balance depends on the payment, since a larger payment each month means less interest added each month. Here's what I used:
annualInterestRate = 0.2
init_balance = 3926
monthlyInterestRate = annualInterestRate/12.0
init_payment = 10
def owedBalance(payment,balance):
""" Calculate total owed balance after one year
given an initial balance and montly payment"""
for month in range(12):
balance = (balance - payment) * (monthlyInterestRate + 1)
return payment*12 + balance
def CheckMinimumPayment(payment,balance):
"Checking if payment is in correct balance"
while (payment*12 < owedBalance(payment, balance)):
payment += 10
return payment
min_payment = CheckMinimumPayment(init_payment,init_balance)
print("Lowest Payment: {}".format(min_payment))

Categories

Resources