Figuring out money change in python - python

I have an assignment where I have to prompt the user for cost of a product and amount paid, I have to output change in pennies, dimes, quarters, $1, $5, $20, $50, and $100, for example: The cost of the item is $19.99 and the client pays with a $50 bill. The change to be provided is 1 $20 bill, one $10 bill, and one penny.
I am confused how to get an output like that though, any help would be greatly appreciated, heres what I have so far
cost = float(input('Cost: '))
amount_paid = float(input('Amount paid: '))
penny = 0.01
dime = 0.10
quarter = 0.25
dollar_1 = 1.00
dollar_5 = 5.00
dollar_10 = 10.00
dollar_20 = 20.00
dollar_50 = 50.00
dollar_100 = 100.00
change = cost - amount_paid
if amount_paid < cost:
print('Error')
I dont know what to do next

A common misstep here is to use floats. You should instead convert everything to the smallest whole unit (a cent) and use integer math. Floating point math is...fuzzy.
currencies = {"penny": 1,
"nickel": 5,
"dime": 10,
"quarter": 25,
"dollar": 1_00,
"five": 5_00,
"ten": 10_00,
"twenty": 20_00,
"fifty": 50_00,
"hundred": 100_00}
# never seen that numeric notation before? It's safe to embed underscores
# in numerical literals! It's often used for large numbers in place of
# commas, but it makes sense here in place of a period.
Then you should only need to define a dictionary for the result, and use divmod to find how many of the denomination can fit in the amount left due.
change_due = {}
for denomination, amt in reversed(currencies.items()):
if amt < amt_due:
d, m = divmod(amt_due, amt)
change_due[denomination] = d
amt_due = m

welcome to stackoverflow! I wrote the code for you and this is how it works. Basically it sees each currency and uses integer division // to see how many integers can fit in. It then subtracts that amount from the remaining change and the process continues. Please ask if you don't understand something, or if you think there is an error.
Code:
cost = float(input('Cost: '))
amount_paid = float(input('Amount paid: '))
penny = 0.01
dime = 0.10
quarter = 0.25
dollar_1 = 1.00
dollar_5 = 5.00
dollar_10 = 10.00
dollar_20 = 20.00
dollar_50 = 50.00
dollar_100 = 100.00
changeTypes = {dollar_100:0,dollar_50:0,dollar_20:0,dollar_10:0,dollar_5:0,dollar_1:0,quarter:0,dime:0,penny:0}
change = amount_paid-cost
if amount_paid < cost:
print('Error: InsufficientFunds')
for changeType in changeTypes:
numAmount = max(0,change//changeType)
change-=numAmount*changeType
changeTypes[changeType] = int(numAmount)
print(changeTypes)
P.S you should make this a function, it shouldn't be too hard.

You could do this good with dictionaries, but without using still there are many ways to go about this, options are endless, heres one idea
def get_bills(change, value):
if change//value > 0:
bills = change//value
change -= bills * value
return bills, change
else:
return 0, change
cost = float(input('Cost: '))
paid = float(input('Amount Paid: '))
while paid < cost:
paid = float(input('Amount Paid: '))
change = paid - cost
hundreds, change, = get_bills(change, 100)
fifties, change, = get_bills(change, 50)
twenties, change = get_bills(change, 20)
tens, change = get_bills(change, 10)
fives, change = get_bills(change, 5)
ones, change = get_bills(change, 1)
quarters, change = get_bills(change, .25)
dimes, change = get_bills(change, .1)
nickels, change = get_bills(change, .05)
pennies = round(change * 100)
print(f"Hundreds: {hundreds}, Fifties: {fifties}, Twenties: {twenties}," +
f" Tens: {tens}, Fives: {fives}, Ones: {ones}, Quarters: {quarters}," +
f" Dimes: {dimes}, Nickels: {nickels}, Pennies: " +
f"{pennies}")

bill = float(input())
paid = float(input())
Available = {100.0:0,50.0:0,20.0:0,10.0:0,5.0:0,1.0:0,0.25:0,0.10:0,0.01:0}
due = paid-bill
for change in sorted(Available,reverse = True):
amt= max(0,due//change)
due-=amt*change
Available[change] = int(amt)
print(Available)

I know this is a late response but maybe it can help someone.
Below is a code for doing exactly what you want. The program iterates through the notes available from largest to smallest and calculates how many times the current note may be used to deduct from the remaining change to be given.
Finally returning a list containing the notes used to reach the sum required.
# Available notes for change
notes = [500, 200, 100, 50, 20, 10]
def change_notes(change, notes):
notes_out = []
for note in notes:
print(f"current note is {note}")
sleep(1)
while change > 0 and note <= change:
if change - note >= 0:
change -= note
notes_out.append(note)
print(f"change is {change}")
sleep(1)
if change == 0:
break
return notes_out

Related

Calculate change from paid amount

Why is this code creating an infinite loop? I would think this should be an appropriate solution for this type of problem. For example, if the price was $5 and you paid $5.47, the program would print:
Quarters: 1
Dimes: 2
Nickels: 0
Pennies: 2
However, an infinite loop occurs and I'm not sure why. Anyone know the reason?
price = round(float(input("Enter the price: ")), 2)
print price
paid = round(float(input("Enter the amount paid: ")), 2)
print paid
change = round(float(paid - price), 2)
print change
quarters = 0
dimes = 0
nickels = 0
pennies = 0
while change > 0.00:
print change
if change >= .25:
change = change - .25
quarters += 1
continue
elif change >= .1:
change = change - .1
dimes += 1
continue
elif change >= .05:
change = change - .05
nickels += 1
elif change >= .01:
change = change - .01
pennies += 1
print "Quarters: " + str(quarters)
print "Dimes: " + str(dimes)
print "Nickels: " + str(nickels)
print "Pennies: " + str(pennies)
Rather than dealing with loops, I would suggest just subtracing off the change that you already gathered, prioritizing larger coins.
price = float(input("Enter the price: "))
paid = float(input("Enter the amount paid: "))
change = paid - price
if change < 0:
raise ValueError('Not enough paid')
quarters = change // 0.25
dimes = (change - (0.25 * quarters)) // 0.10
nickels = (change - (0.25 * quarters) - (0.10 * dimes)) // 0.05
pennies = 100 * (change - (0.25 * quarters) - (0.10 * dimes) - (0.05 * nickels))
print("Quarters: {:.0f}".format(quarters))
print("Dimes: {:.0f}".format(dimes))
print("Nickels: {:.0f}".format(nickels))
print("Pennies: {:.0f}".format(pennies))
There's one minor bug in the code which causes the program to only work correctly if price and amount paid are interchanged (e.g. price = 2, paid = 1). But that is not the issue causing the infinite loop.
Your code creates an infinite loop for e.g. the following arguments:
price: 5.6
paid: 5.4
The reason for the infinite loop can be seen from your own print output:
0.009999999999999275
0.009999999999999275
0.009999999999999275
0.009999999999999275
0.009999999999999275
0.009999999999999275
0.009999999999999275
...
Since change < 0.01, no if clause applies and thus the loop is never left.
How could you solve the problem more robustly?
Here's a sketch
from math import floor
change = paid - price
quarters = int(floor(change / 0.25))
change -= quarters * 0.25
dimes = int(floor(change / 0.1))
change -= dimes * 0.1
nickels = int(floor(change / 0.05))
change -= nickels * 0.05
pennies = int(floor(change / 0.01))
change -= pennies * 0.01
remaining = change
print("Quarters:", quarters)
print("Dimes:", dimes)
print("Nickels:", nickels)
print("Pennies:", pennies)
Personally I would also condense this into a loop over the coin type:
increments = {"quarter":0.25, "dimes": 0.1, "nickels": 0.05, "pennies": 0.01}
change_parts = {}
for inc_name, inc in increments.items():
amount = int(floor(change / inc))
print(inc_name, inc, amount)
change -= amount * inc
change_parts[inc_name] = amount
for inc_name, amount in change_parts.items():
print(inc_name + ":", amount)

algorithm that calculates a minimum amount to be paid to pay off a balance in 12 months

I'm struggling with a problem that calculates the minimum fixed monthly payment needed in order pay off a credit card balance within 12 months. By a fixed monthly payment, I mean a single number which does not change each month, but instead is a constant amount, multiple of 10 and the same for all months, that will be paid each month. ( it is possible for the balance to become negative using this payment scheme, which is OK)
So as input I have
original_balance = 3329
annualInterestRate = 0.2
From this I'm calculating the followings :
after_12_months_interest = original_balance
monthlyInterestRate = round(annualInterestRate/12.0,2)
monthly_payment = 10
total_paid = 0
for i in range(0,12):
after_12_months_interest = after_12_months_interest + (annualInterestRate/12.0)*after_12_months_interest
while total_paid < after_12_months_interest:
new_balance = 0
unpaid_balance = original_balance - monthly_payment
total_paid = 0
for i in range(0, 13):
total_paid = total_paid + monthly_payment
if total_paid < after_12_months_interest:
monthly_payment = monthly_payment + 10
print "Lowest Payment: ", monthly_payment
My problem I have is that I end up having a monthly_payment just a little more than I should have it. In this case the return for the monthly_payment is 320 instead of 310. For all use cases I've tried the monthly_payment it's slightly more than it should be.
Anyone can give me a hint or an idea on what I'm doing wrong please. Thank you
Mandatory one-liner
from itertools import count
print(next(payment for payment in count(0, 10)
if sum(payment*(1+monthly)**i for i in range(12)) > original_balance*(1+annual)))
What this does:
next takes the first element of an iterator.
count tries values from 0 to infinity (only each time next is called, and only until a value is returned)
sum(payment*(1+monthly)**i for i in range(12)) That's the combined value of the payments. Each payment is worth itself plus all the saved interests (the earlier you repay, the less interest you'll owe later)
original_balance*(1+annual) is indeed the total value if nothing is repayed.
Alternative
print(next(payment for payment in count(0, 10)
if reduce(lambda x,_:(x - payment)*(1+monthly), range(12), original_balance) <= 0))
This one computes the combined remainder of the debt by reduceing the original_balance 12 times.

Python-Modulus-Stuck with a coin-for-given-dollar-amount scenario

Specs: Ubuntu 13.04, Python 3.3.1
General Background: total beginner to Python;
Question-specific background: I'm exhausted trying to solve this problem, and I'm aware that, besides its instructional value for learning Python, this problem is boring and does not in any way make this world a better place :-( So I'd be even more grateful if you could share some guidance on this exhausting problem. But really don't want to waste your time if you are not interested in this kind of problems.
What I intended to do: "Calculate the number of basic American coins given a value less than 1 dollar. A penny is worth 1 cent, a nickel is worth 5 cents, a dime is worth 10 cents,
and a quarter is worth 25 cents. It takes 100 cents to make 1 dollar. So given an amount less than 1 dollar (if using floats, convert to integers for this exercise), calculate the number of each type of coin necessary to achieve the amount, maximizing the number of larger denomination coins. For example, given $0.76, or 76 cents, the correct output would be "3 quarters and 1 penny." Output such as "76 pennies" and "2 quarters, 2 dimes, 1 nickel, and 1 penny" are not acceptable."
What I was able to come up with:
penny = 1
nickel = 5
dime = 10
quarter = 25
i = input("Please enter an amount no more than 1 dollar(in cents): ")
i = int(i)
if i > 100:
print ("Please enter an amount equal or less than 100. ")
elif i >= quarter:
quarter_n = i % quarter
i = i - quarter * quarter_n
if i >= dime:
dime_n = i % dime
i = i - dime * dime_n
if i >= nickel:
nickel_n = i % nickel
i = i - nickel * nickel_n
if i >= penny:
penny_n = i % penny
print (quarter_n,"quarters,",dime_n,"dimes",nickel_n,"nickels",penny_n,"pennies")
else:
if i >= penny:
penny_n = i % penny
print (quarter_n,"quarters,",dime_n,"dimes",penny_n,"pennies")
else:
if i >= nickel:
nickel_n = i % nickel
i = i - nickel * nickel_n
if i >= penny:
penny_n = i % penny
print (quarter_n,"quarters,",nickel_n,"nickels",penny_n,"pennies")
else:
if i >= penny:
penny_n = i % penny
print (quarter_n,"quarters,",penny_n,"pennies")
else:
if i >= dime:
dime_n = i % dime
i = i - dime * dime_n
if i >= nickel:
nickel_n = i % nickel
i = i - nickel * nickel_n
if i >= penny:
penny_n = i % penny
print (dime_n,"dimes",nickel_n,"nickels",penny_n,"pennies")
else:
if i >= penny:
penny_n = i % penny
print (dime_n,"dimes",penny_n,"pennies")
else:
if i >= nickel:
nickel_n = i % nickel
i = i - nickel * nickel_n
if i >= penny:
penny_n = i % penny
print (nickel_n,"nickels",penny_n,"pennies")
else:
if i >= penny:
penny_n = i % penny
print (penny_n,"pennies")
This solution, though the best I could come up with, does not work as expected when fed with actual input numbers. And I'm unable to figure out why. Besides, I know that even from sheer size of the code that something is wrong. I searched for similar questions but the closest I got was one that dealt with very difficult math which I couldn't understand.
My question: I know I can't ask for a complete solution because that's down to me to figure it out. I'll appreciate either a) general pointer on the correct line of thinking b) critiques to my current code/line of thinking so that I might be able to improve it.
Thank you for taking the time, even just reading this!
I think your solution may actually be working if you do a "find and replace" for all the mod operators %, switching in integer division //.
Say you have 76 cents and want to find the number of quarters. Using 76 % 25 results in 1 whereas 76 // 25 is 3.
With regard to the code, you should probably be thinking in terms of iterating over the possible coin values rather than a huge if, elif mess.
Try something like this. The only part that may need some explaining is using divmod but its really just a tuple of the integer division, modulo result. You can use that to get the number of coins and the new amount, respectively.
def coins_given(amount):
coins = [(25, 'quarter'), (10, 'dime'), (5, 'nickel'), (1, 'penny')]
answer = {}
for coin_value, coin_name in coins:
if amount >= coin_value:
number_coin, amount = divmod(amount, coin_value)
answer[coin_name] = number_coin
return answer
print coins_given(76)
# {'quarter': 3, 'penny': 1}
i think your algorithm is too complicated,
you don't need all the elifs and the elses
just check with and if and then modidy the remaining amount until you get to zero
something like this
penny = 1
nickel = 5
dime = 10
quarter = 25
q = 0
d = 0
n = 0
p = 0
i = input("Please enter an amount no more than 1 dollar(in cents): ")
i = int(i)
if i>=25:
q = i/quarter
i %= quarter
if i>=10:
d = i/dime
i%=dime
if i>=5:
n = i/nickel
i %= nickel
if i>0:
p = i/penny
i = 0
print "The coins are %i quarters, %i dimes, %i nickels and %i pennys." %(q , d, n, p)
>>>
Please enter an amount no more than 1 dollar(in cents): 99
The coins are 3 quarters, 2 dimes, 0 nickels and 4 pennys.
>>>
Please enter an amount no more than 1 dollar(in cents): 76
The coins are 3 quarters, 0 dimes, 0 nickels and 1 pennys.
dime=10
nickel=5
penny=1
quarter=25
def change(cents):
changeIs = ""
qs = cents/quarter
cents %= quarter
if qs > 0 :
changeIs += str(qs) + " quarter(s)"
ds = cents/dime
cents %= dime
if ds > 0 :
changeIs += " " + str(ds) + " dime(s)"
ns = cents/nickel
cents %= nickel
if ns > 0 :
changeIs += " " + str(ns) + " nickel(s)"
if cents > 0 :
changeIs += " " + str(cents) + " cent(s)"
return changeIs
if __name__ == '__main__':
cents=int(raw_input("Enter the change: "))
print change(cents)

if/elif/else statement help with money

Updated my new code at the bottom of the page as an answer.
So for my CS 170 class, we have to make a program that has user input for less than $10 and change is returned in the least amount of coins, no bills or 50 cent pieces. For the most part the program does well except when you run into a x.x0
e.g.:
Python 2.7.2 (v2.7.2:8527427914a2, Jun 11 2011, 15:22:34)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>>
Amount due:
7.80
Amount in return
2.20.
Quaters in return 8.
Dimes in return 0.
Nickels in return 4.
>>>
the program completely skips over the dimes section and straight to nickels providing 4 as a solution when the least amount should be 8 quarters, 2 dimes and end. Also I'm not really skilled in loops too much, but I know this would be possible and a lot shorter code, and cleaning up the code advice would be nice as well. Thanks for any help!
# optional.py
# Calculating the least amount of change in return for a $10 bill.
## amount due
due = input("Amount due:\n ")
## if amount is more than 10, exit program
if due > 10.00:
print "Please enter a number lower then 10.00."
exit()
## if amount is less than 0, exit program
if due < 0:
print "Please enter a number greater than 0.00."
exit()
## subtract amount from 10
else:
change = 10.00 - due
print "Amount in return\n %0.2f." % change
## if amount is 0, no change
if change == 0:
print "No change in return."
## passes expression if previous not met
pass
elif change >= .25:
## setting q, dividing change by .25
q = change / .25
## maaking q an integer
quaters = int(q)
print "Quaters in return %r." % quaters
## subtracting quaters from chane
change = change - (quaters *.25)
if change < .10:
pass
elif change >= .10 <= .24:
d = change * .1
dimes = int(d)
print "Dimes in return %r." % dimes
change = change - (dimes * .1)
if change < .05:
pass
elif change >=.05 <=.09:
n = change / .05
nickels = int(n)
print "Nickels in return %r." % nickels
change = change - (nickels * .05)
if change == .01:
pennies = change / .01
print "Pennies in return %r." % pennies
elif change >=.01 <=.04:
p = change / .01
print "Pennies in return %0.0f." % p
There are a few changes you could make to clean up this code, and one of them might fix your problem. First, pass does absolutely nothing. It is usually used as a placeholder for a loop or function that will be filled in later. Also, the conditions of your elif statements are mutually exclusive with the if statements they follow, so
if change == 0:
print "No change in return."
## passes expression if previous not met
pass
elif change >= .25:
## setting q, dividing change by .25
q = change / .25
## maaking q an integer
quaters = int(q)
print "Quaters in return %r." % quaters
## subtracting quaters from chane
change = change - (quaters *.25)
can be rewritten as
if change >= .25:
## setting q, dividing change by .25
q = change / .25
## making q an integer
quaters = int(q)
print "Quaters in return %r." % quaters
## subtracting quaters from change
change = change - (quaters *.25)
for each if/elif statement. Also, in the statement
if change >=.01 <=.04:
you are testing whether
change >= .01 and .01 <= .04
To make it do what you want, the statement should be rewritten as
if .01 <= change <= .04
In addition, you are using floating point numbers, which often lead to rounding errors. To avoid these errors, I would suggest either representing your money as an integer number of cents and multiply all of the numbers in your problem by 100 or use something with fixed point numbers like python's decimal module.
This is not doing what you expect:
elif change >= .10 <= .24:
It looks like you intend something like:
elif change >= .10 and change <= .24:
or Python also supports:
elif .10 <= change <= .24:
However, you will next run into floating point rounding problems of various kinds. I suggest you first convert the input number to an integer number of cents, and perform all your calculations in cents. Avoid floating point numbers when dealing with money.
So I got it worked out in a better format with cleaner print code. Thanks for the help guys!
If anyone wants to know the difference between the 2 codes, it's getting it out of floating point like the others suggested and converting what is needed to integers, multiplying the integers by the specific amount, say a quarter, and then subtracting int * coin/bill from the change. Worked out well. I tried experimenting with a for statement, but that didn't turn out too well since I don't know a lot about it yet either. Until next time...
Again thanks guys!
Here's the finished code for anyone wondering about it:
import sys
due = input("Please enter the amount due on the item(s):\n ")
# if over $10, exit
if due > 10:
print "Please enter an amount lower then 10."
sys.exit(1)
## if under/equal 0, exit
if due <= 0:
print "Please enter an amount greater than 0."
sys.exit(2)
## 10 - due = change, converts change into cents by * by 100 (100 pennies per dollar)
else :
change = 1000 - (due * 100)
## if change is 0, done
if change == 0:
print "No change in return!"
## if not 0 makes change2 for amount in return
else:
change2 = change / 100
print "Amount in return:\n $%.2f." % change2
## if change > 500, subract 500 and you get 1 $5 bill
if 500.0 <= change:
bill_5 = change / 500
b5 = int(bill_5)
change = change - 500
## if change is over 100, change divided by 100 and subtracted from change for quaters
if 100.0 <= change:
dollars = change / 100
dollar = int(dollars)
change = change - (dollar * 100)
if 25 <= change < 100:
quaters = change / 25
quater = int(quaters)
change = change - (quater * 25)
if 10 <= change <= 24:
dimes = change / 10
dime = int(dimes)
change = change - (dime * 10)
if 5 <= change < 10:
nickels = change / 5
nickel = int(nickels)
change = change - (nickel * 5)
if 0 < change < 5:
pennies = change / 1
penny = int(pennies)
change = change - (penny * 1)
print "Change in return:\n $5:%i\n $1:%i\n Quaters:%i\n Dimes:%i\n Nickels:%i\n Pennies:%i " % (
b5, dollar, quater, dime, nickel, penny )
if 0 >= change:
print "Done!"

Python: smarter way to calculate loan payments

How to calculate the monthly fee on a loan?
Given is:
a: an amount to loan.
b: the loan period (number of months).
c: the interest rate p.a. (interests is calculated and added every month, 1/12 of the interest is added. So if the interest is on 12%, 1% interest is added every month).
d: the amount of money owed after the end of the period.
This problem is a bit different than the usual since, the goal is not to have the loan payed after the loan period has ended, but to still owe an amount that is given. I have been able to find an algorithm so solve the problem if I wanted to pay the entire amount, but it will of course not work for this problem where the goal is to end up owing a given amount rather than not owing anything.
I managed to make a solution to this problem by starting with an guess and then keep on improving that guess until it was close enough. I wondered however, if there is a better way to simply calculate this, rather than just guessing.
Edit: Here's how I'm doing it now.
def find_payment(start, end, months, interest):
difference = start
guess = int(start / months * interest)
while True:
total = start
for month in range(1, months + 1):
ascribe = total * interest / 12
total = total + ascribe - guess
difference = total - end
# See if the guess was good enough.
if abs(difference) > start * 0.001:
if difference < 0:
if abs(difference) < guess:
print "payment is %s" % guess
return evolution(start, guess, interest, months)
else:
mod = int(abs(difference) / start * guess)
if mod == 0:
mod = 1
guess -= mod
else:
mod = int(difference / start * guess)
if mod == 0:
mod = 1
guess += mod
else:
print "payment is %s" % guess
return evolution(start, guess, interest, months)
evolution is just a function that displays how the loan would look like payment for payment and interest for interest, summing up total amount of interest paid etc.
An example would be if I wanted to find out the monthly payments for a loan starting with $100k and ending at $50k with an interest of 8% and a duration of 70 months, calling
>>> find_payment(100000, 50000, 70, 0.08)
payment is 1363
In the above case I would end up owing 49935, and I went through the loop 5 times. The amount of times needed to go through the loop depends on how close I want to get to the amount and it varies a bit.
This is a basically a mortgage repayment calculation.
Assuming that start is greater than end, and that interest is between 0 and 1 (i.e. 0.1 for 10% interest)
First consider the part of the payment you want to pay off.
Principal = start - end
The monthly payment is given by:
pay_a = (interest / 12) / (1 - (1+interest/12) ^ (-months))) * Principal
You then need to consider the extra interest. Which is just equal to the remaining principal times the monthly interest
pay_b = interest / 12 * end
So the total payment is
payment = (interest / 12) * (1 / (1 - (1+interest/12) ^ (-months))) * Principal + end)
On the example you gave of
Start: 100000
End: 50000
Months: 70
Interest: 8%
pay_a = 896.20
pay_b = 333.33
Payment = 1229.54
When I tested these values in Excel, after 70 payments the remaing loan was 50,000. This is assuming you pay the interest on the notional before the payment is made each month.
Perhaps the easiest way to think about this is to split the loan in two parts, one part which is to be repaid in full and another part where you don't pay off anything. You have already computed the monthly fee for the first part.
You can keep paying the interest of every month; then, you will alway owe the same amont.
Owe_1 = a
Int_2 = Owe_1*(InterestRate/12)
Pay_2 = Int_2
Owe_2 = Owe_1 + Int_2 - Pay_2 # ==> Owe_1 + Int_2 - Int_2 = Owe_1
Int_3 = Owe_2*(InterestRate/12)
Pay_3 = Int_3
Owe_3 = Owe_2 + Int_3 - Pay_3 # ==> Owe_2 + Int_3 - Int_3 = Owe_2 = Owe_1
python code to calculate emi
class EMI_CALCULATOR(object):
# Data attributes
# Helps to calculate EMI
Loan_amount = None # assigning none values
Month_Payment = None # assigning none values
Interest_rate = None #assigning none values
Payment_period = None #assigning none values
def get_loan_amount(self):
#get the value of loan amount
self.Loan_amount = input("Enter The Loan amount(in rupees) :")
pass
def get_interest_rate(self):
# get the value of interest rate
self.Interest_rate = input("Enter The Interest rate(in percentage(%)) : ")
pass
def get_payment_period(self):
# get the payment period"
self.Payment_period = input("Enter The Payment period (in month): ")
pass
def calc_interest_rate(self):
# To calculate the interest rate"
self.get_interest_rate()
if self.Interest_rate > 1:
self.Interest_rate = (self.Interest_rate /100.0)
else:
print "You have not entered The interest rate correctly ,please try again "
pass
def calc_emi(self):
# To calculate the EMI"
try:
self.get_loan_amount() #input loan amount
self.get_payment_period() #input payment period
self.calc_interest_rate() #input interest rate and calculate the interest rate
except NameError:
print "You have not entered Loan amount (OR) payment period (OR) interest rate correctly,Please enter and try again. "
try:
self.Month_Payment = (self.Loan_amount*pow((self.Interest_rate/12)+1,
(self.Payment_period))*self.Interest_rate/12)/(pow(self.Interest_rate/12+1,
(self.Payment_period)) - 1)
except ZeroDivisionError:
print "ERROR!! ZERO DIVISION ERROR , Please enter The Interest rate correctly and Try again."
else:
print "Monthly Payment is : %r"%self.Month_Payment
pass
if __name__ == '__main__':# main method
Init = EMI_CALCULATOR() # creating instances
Init.calc_emi() #to calculate EMI
for more info visit : https://emilgeorgejames.wordpress.com/2015/07/29/python-emi-equated-monthly-installment-calculator/
This rather a detailed way but will give the whole payment as well
# Mortgage Loan that gives the balance and total payment per year
# Function that gives the monthly payment
def f1 (principle,annual_interest_rate,duration):
r = annual_interest_rate/1200
n = duration*12
a=principle*r*((1+r)**n)
b= (((1+r)**n)- 1)
if r > 0 :
MonthlyPayment = (a/b)
else :
MonthlyPayment = principle/n
return MonthlyPayment
# Function that gives the balance
def f2 (principle,annual_interest_rate,duration,number_of_payments):
r = annual_interest_rate/1200
n = duration*12
a= ((1+r)**n)
b= ((1+r)**number_of_payments)
c= (((1+r)**n)-1)
if r > 0 :
RemainingLoanBalance = principle*((a-b)/c)
else :
RemainingLoanBalance = principle*(1-(number_of_payments/n))
return RemainingLoanBalance
# Entering the required values
principle=float(input("Enter loan amount: "))
annual_interest_rate=float(input("Enter annual interest rate (percent): "))
duration=int(input("Enter loan duration in years: "))
# Output that returns all useful data needed
print ("LOAN AMOUNT:",principle,"INTEREST RATE (PERCENT):",annual_interest_rate)
print ("DURATION (YEARS):",duration,"MONTHLY PAYMENT:",int(f1(principle,annual_interest_rate,duration)))
k=duration+1
BALANCE=principle
total=0
for i in range (1,k):
TOTALPAYMENT= f1(BALANCE,annual_interest_rate,k-i)*12
total+= TOTALPAYMENT
BALANCE= f2(principle,annual_interest_rate,duration,12*i)
print("YEAR:",i,"BALANCE:",int(BALANCE),"TOTAL PAYMENT",int(total))
How about this?
def EMI_calc(principle, rate, time, frequency):
return (principle / ((1-((1+(rate/frequency))**(-1*(time*frequency))))/(rate/frequency)))
print("""
----- Welcome to EMI programe for Python -----
""")
print("\n You have chosen to know the EMI for Loan.\n")
input('\nTo Continue Press ENTER --- to ABORT Press ctrl+c > \n')
print("\nPlease Enter amount of Loan to be taken: >\n")
principle = int(input())
print("\nEnter rate of interst (%): >\n")
rate = float(input())/100
print("\nEnter Term (Years): >\n")
time = float(input())
print("\nPlease enter the frequency of installments) : >\n")
frequency = int(input())
EMI = round(EMI_calc(principle, rate, time, frequency),0)
print("""
---------------------------------------------------------------------
""")
print(f"""
The EMI for Loan of Rs.{principle};
at interest rate of {rate*100} % for {time} years;
would be: Rs.""", EMI)
print("""
---------------------------------------------------------------------
""")
Here is a code snippet using numpy functions. This shows you the payment, principal, interest, instalment and total_amount each month. Run it and see the output. You can also check the syntax for Excel "IPMT()" and "PPMT()" functions for more explanation of the arguments.
https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.pmt.html#numpy.pmt
import math
import numpy as np
rate = 0.08
start_amount = 100000.0
end_amount = 50000.0
diff_amount = start_amount - end_amount
# nr_years = 4
payment_frequency = int (12)
nr_months = 70 # = nr_years * payment_frequency
per_np = np.arange (nr_months) + 1 # +1 because index starts with 1 here
pay_b = rate / payment_frequency * end_amount
ipmt_np = np.ipmt (rate / payment_frequency, per_np, nr_months, diff_amount) - pay_b
ppmt_np = np.ppmt (rate / payment_frequency, per_np, nr_months, diff_amount)
for payment in per_np:
idx = payment - 1
principal = math.fabs (ppmt_np [idx])
start_amount = start_amount - principal
interest = math.fabs (ipmt_np [idx])
instalment = principal + interest
print payment, "\t", principal, "\t", interest, "\t\t", instalment, "\t\t", start_amount
print np.sum (ipmt_np)

Categories

Resources