I am trying to solve a question regarding lottery winnings. As we all know that after a person wins a lottery amount, they don't always take the full amount. They get taxed in different brackets and I am trying to create a python program which tells us the amount that we are taxed on our winnngs.
Before any taxes are assessed, the winner is given a standard deduction of $6300 and a personal exemption of $4000. So before we find out how much amount is taxed, we find the taxable amount by the formula
taxablewinnings = winnings-(Standard Deduction+Personal Exemption)
After that the winning amount is categorized in these amount brackets.
$0 to $9,225----10%
$9,225 to $37,450----15%
$37,450 to $90,750----25%
$90,750 to $189,300----28%
$189,300 to $411,500----33%
$411,500 to $413,200----35%
$413,200+ ----39.6%
For example. If a person wins $54000
taxablewinnings = $54000-$6300-$4000
=$43,700 is the amount which will be taxed. Of that amount:
$9225 is taxed at 10% = $922.50
leaving $34,475 not yet taxed
$28,225 is taxed at 15% = $4233.75
leaving $6,250 not yet taxed
$6,250 is taxed at 25% = $1,562.50
Total owed = 922.5 + 4233.75 + 1562.5 = $6718.75 (or $6,719 rounded)
Here is my code.
winnings = float(input("Please enter your Winning amount"))
tax = 0
standardDeduction = 6300
personalExemption = 4000
taxablewinnings = winnings - (standardDeduction+personalExemption)
if taxablewinnings > 0 and taxablewinnings <= 9225:
rate1 = 9225*0.10
remainder1 = taxablewinnings-9225
if taxablewinnings > 9225 and taxablewinnings <= 37450:
rate2 = remainder1*0.15
remainder2 = taxablewinnings-37450
if taxablewinnings > 37450 and taxablewinnings <= 90750:
rate3 = remainder2*0.25
remainder3 = taxablewinnings-90750
if taxablewinnings > 90750 and taxablewinnings <= 189300:
rate4 = remainder3*0.28
remainder4 = taxablewinnings-189300
if taxablewinnings > 189300 and taxablewinnings <= 411500:
rate5 = remainder4*0.33
remainder5 = taxablewinnings-411500
if taxablewinnings > 411500 and taxablewinnings <= 413200:
rate6 = remainder5*0.33
remainder6 = taxablewinnings-413200
if taxablewinnings > 413200:
rate7 = remainder6*0.396
else:
print("Invalid winnings input")
if(winnings > 0):
print("Your tax is: $%f" % tax)
I am getting the error
rate3 = remainder2*0.25 NameError: name 'remainder2' is not defined
If taxablewinnings is greater than 37450, this error will always occur because remainder2 is getting defined ONLY if taxablewinnings is in the 37450 to 92250 range.
I rewrote certain parts of your program:
winnings = int(raw_input("Amount won: "))
STD_DEDUCTION = 6300
PERSONAL_EXEMPTION = 4000
TAX_BRACKETS = [(0, 0), (9225, .1), (37450, .15), (90750, .25),
(189300, .28), (411500, .33), (413200, .35)]
taxable = winnings - (STD_DEDUCTION + PERSONAL_EXEMPTION)
tax = 0
for i in xrange(1, len(TAX_BRACKETS)):
value = TAX_BRACKETS[i][0] - TAX_BRACKETS[i-1][0]
percent = TAX_BRACKETS[i][1]
amt_to_tax = taxable if taxable < value else value
tax += amt_to_tax * percent
taxable -= amt_to_tax
tax += taxable * .396
print "Winnings: {}\nTax: {}\nWinnings after taxes: {}".format(
winnings, tax, winnings - tax)
I think that this solution is a little bit more robust than your solution, but it still really does encompass the spirit of your code.
going by your explanations, because I am from outside of usa, then this may be what you want
standardDeduction = 6300
personalExemption = 4000
tax_brackets = [ ( 0, 9225, 0.10),
( 9225, 37450, 0.15),
( 37450, 90750, 0.25),
( 90750, 189300, 0.28),
(189300, 411500, 0.33),
(411500, 413200, 0.35),
(413200, None, 0.396) ]
def calculate_tax(total):
no_tax = standardDeduction + personalExemption
taxable = total - no_tax
total_tax = 0.0
for min_val, max_val, tax in tax_brackets :
if taxable <= 0:
break
amount = (max_val - min_val) if max_val is not None else min_val
if taxable <= amount:
amount = taxable
total_tax += amount * tax
taxable -= amount
return total_tax
test
>>> calculate_tax(54000)
6718.75
>>>
Instead of doing it one use only as in your code, is best to make it a function so it can be used multiples times, now about the code, the first part is self explanatory, now the interesting part the for loop: here we iterate over the tax_brackets while we have something to tax or until we run out of brackets, as you explain we take a amount equal to the difference between the boundaries of the bracket but if that amount excede the taxable money we take the leftover instead, then apply the tax of the current bracket and subtract used amount.
EDIT
The previous function can be expressed in terms of if as follow
standardDeduction = 6300
personalExemption = 4000
no_tax = standardDeduction + personalExemption
total = float(input("Please enter your Winning amount: "))
taxable = total - no_tax
total_tax = 0.0
if taxable > 0: # brackets 1
amount = 9225 # - 0
if taxable <= amount:
amount = taxable
total_tax += amount * 0.1
taxable -= amount
if taxable > 0: # brackets 2
amount = 37450 - 9225
if taxable <= amount:
amount = taxable
total_tax += amount * 0.15
taxable -= amount
if taxable > 0: # brackets 3
amount = 90750 - 37450
if taxable <= amount:
amount = taxable
total_tax += amount * 0.25
taxable -= amount
if taxable > 0: # brackets 4
amount = 189300 - 90750
if taxable <= amount:
amount = taxable
total_tax += amount * 0.28
taxable -= amount
if taxable > 0: # brackets 5
amount = 411500 - 189300
if taxable <= amount:
amount = taxable
total_tax += amount * 0.33
taxable -= amount
if taxable > 0: # brackets 6
amount = 413200 - 411500
if taxable <= amount:
amount = taxable
total_tax += amount * 0.35
taxable -= amount
if taxable > 0: # brackets 7
amount = 413200
if taxable <= amount:
amount = taxable
total_tax += amount * 0.396
taxable -= amount
if total > 0:
print("you win",total,"and you have to paid",total_tax,"in tax")
else:
print("Invalid winnings input")
(this is an almost literal translation of the function step by step)
test
Please enter your Winning amount: 54000
you win 54000.0 and you have to paid 6718.75 in tax
>>>
The answer to your original question is, the symbol is undefined because the definition appears inside an un-taken 'if' statement, for example, in this block:
if taxablewinnings > 9225 and taxablewinnings <= 37450:
rate2 = remainder1*0.15
remainder2 = taxablewinnings - 37450
If your winnings were less than 9225, the code remainder2 = taxablewinnings - 37450 is never executed. And if your winnings are greater than 37450, the block is never executed because they are too high. You have a logic error here. (And throughout.)
Also, how do you handle the case where the amount to be taxed is NOT the full amount?
For example, if my taxable winnings are 40000, that certainly qualifies as being taxablewinnings > 9225. But 40000 does not match taxablewinnings <= 37450. So you force all my winnings into the higher tax bracket.
Or you would, except that you are looking for a remainder2 that has never been initialized, because you completely skipped the block above.
Instead, you want to take a little bite out of the winnings, even when they are higher than the upper limit of the tax bracket. So if 40000 is the taxable winnings, then tax some amount of it at 0.15, and then go on.
taxes_due = 0.0
if taxablewinnings < 0:
taxablewinnings = 0
if taxablewinnings > 0:
rate = 0.10
lower_limit = 0
upper_limit = 9225
if taxablewinnings <= upper_limit:
taxes_due += rate * (taxablewinnings - lower_limit)
else:
taxes_due += rate * (upper_limit - lower_limit)
if taxablewinnings > 9225:
rate = 0.15
lower_limit = 9225
upper_limit = 37450
if taxablewinnings <= upper_limit
taxes_due += rate * (taxablewinnings - lower_limit)
else:
taxes_due += rate * (upper_limit - lower_limit)
You can (I hope) see the pattern from here. Obviously, the last bracket won't have an upper limit, so it will be a little simpler. Good luck.
Related
income = float(input("your income: "))
if income <= 100000:
initalIncome = income * 0.5
elif income in range (100001,250000):
initalIncome = income * 0.10
elif income in range (250001,500000):
initialIncome = income * 0.15
elif income >= 500001:
initialIncome = income * 0.20
print(initialIncome)
#why is it giving the wrong answer?
#I think there's something wrong with the conditions
I cannot find the right code on how do i find the final tax in this code
I hope this is the answer you looking for, but you did not create the InitialIncome variable. Thus executing your code, this is the result:
income = float(input("your income: "))
if income <= 100000:
initalIncome = income * 0.5
elif income in range (100001,250000):
initalIncome = income * 0.10
elif income in range (250001,500000):
initialIncome = income * 0.15
elif income >= 500001:
initialIncome = income * 0.20
print(initialIncome)
your income: 100
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-1-306fbda6a7e7> in <module>
9 initialIncome = income * 0.20
10
---> 11 print(initialIncome)
NameError: name 'initialIncome' is not defined
Try to add the variable you are looking for with value of 0.
In that case your code works.
def income_calc():
income = float(input("your income: "))
initialIncome = 0
if income <= 100000:
initialIncome = income *0.5
elif income in range (100001, 250000):
initialIncome = income *0.10
elif income in range (250001, 500000):
initialIncome = income *0.15
elif income >= 500001:
initialIncome = income *0.20
return initialIncome
Executing:
You are printing the wrong variable
check your spelling for initialIncome in each condition
im new to coding and am learning python atm. I was writing this simple code for a discount system and it wont work for some weird reason. pls tell me whats wrong with this code
price = (input('Please type the value of your item.'))
if price >= 300:
price = (price + ((price) * (30/100) )
elif price >= 200 and < 300:
price = (price + ((price) * (20/100) )
elif price >= 100 and <200:
print('You need to pay' + price + '$ for your item')
price = (price + ((price) * (10/100) )
This statement isn't valid:
elif price >= 200 and < 300:
It would correctly be written as:
elif price >= 200 and price < 300:
Note that for this to work, price needs to be a numeric value; you need to convert your input() result to a float or int before trying anything mathematical with it!
However, specifying price < 300 isn't necessary in the first place, since this is an elif that can only happen if price >= 300 was false (hence price < 300 is logically implied to be true).
You can also simplify the arithmetic down; this:
price = (price + ((price) * (30/100) )
is really just the same (algebraically) as:
price = price * (1 + 30/100)
which is the same as:
price *= 1.3
Since you're going to end up with floating point numbers in most cases, you probably want to round this output to 2 decimal places:
print('You need to pay' + price + '$ for your item')
which you can do easily with an f-string:
print(f'You need to pay ${price:.2f} for your item')
All together:
price = float(input('Please type the value of your item.'))
if price >= 300:
price *= 1.3
elif price >= 200:
price *= 1.2
elif price >= 100:
price *= 1.1
print(f'You need to pay ${price:.2f} for your item')
change from this:
if price >= 300:
price = (price + ((price) * (30/100) )
elif price >= 200 and < 300:
price = (price + ((price) * (20/100) )
elif price >= 100 and <200:
to this:
if price >= 300:
price = (price + ((price) * (30/100) )
elif price >= 200 and price < 300:
price = (price + ((price) * (20/100) )
elif price >= 100 and price < 200:
I want to use bisection search to find out how much monthly payment should be in order to pay the full amount of balance within 12 months which user will input. However, this code I write goes into the infinite loop,showing "low, high, montlyPayment infinite times." I don't know which code causes this problem since conditional statement seems right to me .
initialBalance = float(raw_input('Enter the outstanding balance on your credit card'))
annualInterestrate = float(raw_input('Enter the annual credit card interest rate as a decimal'))
monthlyInterestrate = round(annualInterestrate, 2)
balance = initialBalance
while balance > 0:
numMonth = 0
balance = initialBalance
low = balance/12.0
high = (balance*(1+(annualInterestrate/12.0))**12.0)/12.0
epsilon = 0.01
monthlyPayment = round((high + low)/2.0, 2)
while abs(monthlyPayment*12.0 - initialBalance) >= epsilon:
print 'low =', low, 'high =', high, 'monthlyPayment =', round(monthlyPayment,2)
if monthlyPayment*12.0 < balance:
low = monthlyPayment
else:
high = monthlyPayment
monthlyPayment = round((high + low)/2.0, 2)
while balance > 0 and numMonth < 12:
numMonth += 1
interest = monthlyInterestrate * balance
balance -= monthlyPayment
balance += interest
balance = round(balance, 2)
print 'RESULT'
print 'monthly payment to pay off debt in 1 year:', monthlyPayment
print 'Number of months needed:', numMonth
print 'Balance:',balance
I have re-coded the above problem as
balance = 120000
annualInterestRate = 0.1
rate=annualInterestRate/12.0
high=(balance * (1 + rate)**12) / 12.0
low=balance/12.0
payment=0
bal_ref=balance
unpaid=balance
N=0
while (abs(unpaid) > .01):
month=0
pay=(high+low)/2
balance=bal_ref
while(month < 12):
unpaid=balance-pay
balance=unpaid + (unpaid * rate)
month +=1
if (abs(unpaid) < .01):
payment=pay
break
elif (unpaid > .01):
low=pay
elif (unpaid < -.01):
high=pay
N+=1
print("Payment:",round(pay,2))
I am supposed to write a code to pay of credit card debts in an year or less where balance and annual interest rate are the inputs and the output is a monthly installment to pay off the debt in an year or less.The remaining math required for the upper bound and lower bound is in the code.Please help.
balance = int(raw_input())
annualInterestRate = float(raw_input())
lowestPayment = balance
monthlyPayment = 0
monthlyUnpaid = 0
temp = balance
monthlyInterest = 0
lowerBound = balance/12
upperBound = balance*((1+annualInterestRate/12.0)**12)/12.0
mid = 0
while upperBound - lowerBound > 0.0000:
mid = (upperBound + lowerBound)/2.0
monthlyPayment = mid
balance = temp
for i in range(1,13):
monthlyUnpaid = balance - monthlyPayment
monthlyInterest = annualInterestRate/12.0 * monthlyUnpaid
balance = monthlyUnpaid + monthlyInterest
if int(balance) <= 0:
upperBound = mid - 1
if monthlyPayment < lowestPayment:
lowestPayment = monthlyPayment
elif int(balance) > 0:
lowerBound = mid + 1
print 'Lowest Payment: '+str(round(lowestPayment,2))
The question is to find the fixed amount you need to pay to a credit card company when -
bal= the amount you need to pay at the beginning of 0th month
N = it is the monthly fixed amount to be to paid to the credit card company such that at the end of the year, you will have paid the total amount
int = interest rate of the credit card company
bal = int(raw_input("Enter balance"))
rate = int(raw_input("enter rate"))
lower_b = bal/12
upper_b = (bal + ((rate*bal)/1200))/12
N= (lower_b+upper_b)/2
def Credit(bal,rate,N):
global upper_b
global lower_b
i=1
k=bal
while (i<13):
print(N)
paid = N
bal = bal - paid
print("Balance remains to be paid is %s" %(round(bal,2)))
Interest = rate * bal /1200
print("The interest added on is %s" %(round(Interest,2)))
bal=bal+Interest
print ("The amount that needs to be payed is %s " %(round(bal,2)))
i=i+1
if bal==0:
return N
elif 50 < bal < 2000 :
lower_b = N
upper_b = upper_b
N = (upper_b +lower_b)/2
return Credit(k,rate,N)
elif -2000<bal< -50:
upper_b = N
lower_b = lower_b
N = (lower_b +upper_b)/2
return Credit(k,rate,N)
elif -50 < bal < 50:
return N
else:
return bal
result=Credit(bal,rate,N)
print(result)
My code never terminates. The problem is the value of N defined in the code is not changing. It remains fixed N = upper_b +lower_b)/2
Using recursion would not be the ideal approach, you also have logic errors including needing to get the interest rate for the month, your initial upper bound should be greater than the principal plus the interest. You can use a while loop with an inner for loop resetting the balance after each unsuccessful inner loop:
balance = int(raw_input("Enter balance"))
int_rate = float(raw_input("enter rate"))
int_rate /= 100
lower_b = balance / 12.
upper_b = ((balance * (1 + (int_rate / 12.0)) ** 12) / 12.0)
payment = (lower_b + upper_b) / 2
def Credit(bal, rate, low, high, pay):
new_b = bal
# calculate monthly interest rate
month_int = rate / 12
while abs(new_b) > 0.001: # use epsilon
# always reset balance
new_b = bal
for _ in range(12): # loop over 12 month range
new_b -= pay # deduct pay
new_b += month_int * new_b
# if we still have a balance we need to take more so set low to current payment
if new_b > 0:
low = pay
# else we took to much so set high to current payment
else:
high = pay
pay = (low + high) / 2.0
return "Lowest monthly payment over 12 months: {}".format(pay)
print(Credit(balance, int_rate, lower_b, upper_b, payment))