This code I wrote for a school assignment. I checked the code with pylint, and pylint reports pointless-statement for all if elif else statements. I don't know how to improve my code, is there someone who could help me out? Thanks
USD = 0.8500
GBP = 1.1700
JPY = 0.0077
RATE = 0.015
FEE_MIN = 2.00
FEE_MAX = 15.00
choise = int(input("Which currency do you want to exchange for euros? "
"1) USD dollar,2) GB pound, 3) JP yen : "))
#USD
if (choise) == 1:
foreign = round(float(input("What amount of dollars do you want to convert"
" to euros? : ")))
euros = round((foreign * USD), 2)
COST = (round((foreign * USD), 2) * RATE)
if COST <= FEE_MIN:
COST = FEE_MIN
elif COST > FEE_MAX:
COST = FEE_MAX
else:
COST
payout = (float(euros) - float(COST))
print("The transactioncost are: {:.2f}.".format(COST))
print("You'll receive {:.2f} euros.".format(payout))
#GBP
if (choise) == 2:
foreign = round(float(input("What amount of pounds do you want to convert"
" to euros? : ")))
euros = round((foreign * GBP), 2)
COST = (round((foreign * GBP), 2) * RATE)
if COST <= FEE_MIN:
COST = FEE_MIN
elif COST > FEE_MAX:
COST = FEE_MAX
else:
COST
payout = (float(euros) - float(COST))
print("The transactioncost are: {:.2f}.".format(COST))
print("You'll receive {:.2f} euros.".format(payout))
#JPY
if (choise) == 3:
foreign = round(float(input("What amount of yen's do you want to convert"
" to euros? : ")))
euros = round((foreign * JPY), 2)
COST = (round((foreign * JPY), 2) * RATE)
if COST <= FEE_MIN:
COST = FEE_MIN
elif COST > FEE_MAX:
COST = FEE_MAX
else:
COST
payout = (float(euros) - float(COST))
print("The transactioncost are: {:.2f}.".format(COST))
print("You'll receive {:.2f} euros.".format(payout))
The problem is here:
else:
COST
Does nothing.
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 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.
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))
My code:
monthlyInterestRate = annualInterestRate/12.0
low = balance/12
high = (balance*(1+monthlyInterestRate)**12)/12
guess = (low+high)/2
unpaidBalance = balance
month = 1
while True:
unpaidBalance= unpaidBalance-guess
while month < 13:
if unpaidBalance <= -0.1:
low = guess
month += 1
elif unpaidBalance >= 0.1:
high = guess
month += 1
else:
break
guess = (low + high)/2
print "Lowest Payment: " + str(round(guess, 2))
When I test it it gets stuck at the line "while month < 13:"
Why does it do this and how do I fix it?
If you break at each loop of inner while, you remains less than 13.
And this goes on and on since you proceed While True and do not update your guess.
I fear you are facing infinite looping there.
Your break statement breaks the closest loop, that is the While month < 13 loop. The next line is not read. guessis not updated. The while True is not broken.
Maybe you wanted to say
while month < 13:
unpaidBalance= unpaidBalance-guess
if unpaidBalance <= -0.1:
low = guess
elif unpaidBalance >= 0.1:
high = guess
month += 1
guess = (low + high)/2
here you are
No is the best solution, but it works
monthlyPaymentRate = (balance*annualInterestRate/12)/((1-(1+annualInterestRate/12)**-12))
interest = monthlyPaymentRate * (annualInterestRate/12)
#print (monthlyPaymentRate)
#print (interest)
monthlyPaymentRate = (monthlyPaymentRate - interest) +1
#print (monthlyPaymentRate)
balanceInit = balance
epsilon = 0.01
low = monthlyPaymentRate
while low*12 - balance > epsilon:
balances = balanceInit
for i in range(12):
minpay = monthlyPaymentRate
unpaybal = balances - minpay
interest = (annualInterestRate /12) * unpaybal
smontfinal = unpaybal + interest
balances = smontfinal
#print('Remaining balance: ' ,round(balances,2) )
if balances <0:
low = -1
break
if balances < 0 :
low = -1
else:
monthlyPaymentRate =monthlyPaymentRate + 0.001
print('Lowest Payment:' ,round(monthlyPaymentRate,2) )