loan calculator

Please support our Python advertiser: Programming Forums - DaniWeb Sister Site
Thread Solved

Join Date: Oct 2009
Posts: 17
Reputation: Mensa180 is an unknown quantity at this point 
Solved Threads: 1
Mensa180 Mensa180 is offline Offline
Newbie Poster

loan calculator

 
1
  #1
Oct 6th, 2009
Hello, I'm very new to python but made this as a sort of exercise. It is a loan calculator that takes into account user input.

  1. r = input('What is your interest rate? ')
  2. t = input('How many payments will you make? ')
  3. la = input('What was the amount of the loan? ')
  4. rt = raw_input('Do you make your payments weekly, monthly, quarterly, or annually? ')
  5.  
  6. r = r + .0
  7.  
  8. r = r / 100
  9.  
  10. rr = r / 52
  11. x = (1.0 + rr) ** t
  12. y = rr / (x - 1.0)
  13. isloanweek = (rr + y) * la
  14.  
  15. rr = r / 12
  16. x = (1.0 + rr) ** t
  17. y = rr / (x - 1.0)
  18. isloanmonth = (rr + y) * la
  19.  
  20. rr = r / 4
  21. x = (1.0 + rr) ** t
  22. y = rr / (x - 1.0)
  23. isloanquarter = (rr + y) * la
  24.  
  25. rr = r / 1
  26. x = (1.0 + rr) ** t
  27. y = rr / (x - 1.0)
  28. isloanannual = (rr + y) * la
  29.  
  30. whatloan = True
  31. while whatloan:
  32. if rt == 'weekly':
  33. print isloanweek
  34. whatloan = False
  35. elif rt == 'monthly':
  36. print isloanmonth
  37. whatloan = False
  38. elif rt == 'quarterly':
  39. print isloanquarter
  40. whatloan = False
  41. elif rt == 'annually':
  42. print isloanannual
  43. whatloan = False
  44. else:
  45. rt = raw_input('Sorry that was not an option, please respond with weekly, monthly, quarterly, or annually: ')
Note:
I moved this post to its own thread. As you look at the code there are many lines of repetitious code, a sign that a function is due. Can anybody help Mensa180 in a nice way to improve the Python coding style?

Mensa180, thanks for the code contribution!
Last edited by vegaseat; Oct 7th, 2009 at 9:56 am. Reason: post needed its own thread
Reply With Quote Quick reply to this message  
Join Date: Jul 2008
Posts: 1,067
Reputation: jlm699 is a jewel in the rough jlm699 is a jewel in the rough jlm699 is a jewel in the rough jlm699 is a jewel in the rough 
Solved Threads: 267
Sponsor
jlm699's Avatar
jlm699 jlm699 is offline Offline
Knows where his Towel is
 
1
  #2
Oct 7th, 2009
Mensa: your code was very well structured and a nice example of reading user input then using it for calculation. Here's how I've modified your code:
  1. def calc_payment(int_rate, num_pmnts, principal, freq):
  2. ''' This function will calculate the payment amount of a loan.
  3. @ Inputs
  4. - int_rate - The interest rate of the loan
  5. - num_pmnts - The number of payments required
  6. - principal - The original amount of the loan (minus down-payment)
  7. - freq - Frequency of payments (weekly, monthly, quarterly, annually)
  8.  
  9. @ Returns
  10. - pmnt_amt - The amount that each payment will be
  11. '''
  12.  
  13. freq_lookup = {'weekly':52, 'monthly':12, 'quarterly':4, 'annually':1}
  14. int_rate = float(int_rate) / 100
  15.  
  16. rr = int_rate / freq_lookup[freq]
  17. x = (1.0 + rr) ** num_pmnts
  18. y = rr / (x - 1.0)
  19. pmnt_amt = (rr + y) * principal
  20.  
  21. return pmnt_amt
  22.  
  23.  
  24. def main():
  25. r = input('What is your interest rate? ')
  26. t = input('How many payments will you make? ')
  27. la = input('What was the amount of the loan? ')
  28. rt = None
  29. while rt not in ['weekly', 'monthly', 'quarterly', 'annually']:
  30. if rt:
  31. rt = raw_input('Sorry that was not an option, please respond with weekly, monthly, quarterly, or annually: ').lower()
  32. else:
  33. rt = raw_input('Do you make your payments weekly, monthly, quarterly, or annually? ').lower()
  34. payment = calc_payment(r, t, la, rt)
  35. print 'Your %s payment will be %.2f' % (rt, payment)
  36.  
  37.  
  38. if __name__ == '__main__':
  39. main()
  40. raw_input('Press Enter to Exit...')
Here are the modifications I made:

1. Moved the payment calculation to a function called calc_payment and added comments explaining what the function does, what inputs it expects and what the output means (this is something that you should get in the habit of doing, as it will help in the future and is good coding practice).

2. I removed the r = r + .0 line and instead consolidated it with the line immediately below it using the built-in float function (which converts the number to floating point, as does adding .0).

3. I added a dictionary lookup for the payment frequency. Each key is the word description that you ask the user for (weekly, monthly, quarterly, annually) and then the value corresponding to each key is the frequency that you were using in the calculations (52, 12, 4, 1 respectively). This allows us to use one calculation instead of doing four and then picking one of the results later.

4. Moved the user input requesting into the "main" function. Also added a statement that you'll see quite frequently when working with Python: if __name__ == '__main__': . This is typically the only statement that is not inside of a function (aside from a main function call or some initialization stuff, which are inside this "if" block). This statement makes sure that the program is running as the 'main' script, and executes accordingly. So now, if another program were to input <script_name> where script_name is the name of this script, that other program would not automatically run the main function and ask the user for input. Then your 'main' program would be able to call <script_name>.calc_payment and make use of it however you'd like.

5. Moved the part that tells the user they provided an incorrect input for frequency to where we get the input. This makes sure we don't do the calculation until the user has given us a correct input. I also used lower to make sure the string is all lower case and a list to validate and make sure their input is kosher.

I think that's about it, but if you have any questions about my modifications, please feel free to ask for further details!
1. Use Code Tags.
2. Homework? Show Effort.
3. Keep discussions on the forum: no PMs
Reply With Quote Quick reply to this message  
Join Date: Oct 2009
Posts: 17
Reputation: Mensa180 is an unknown quantity at this point 
Solved Threads: 1
Mensa180 Mensa180 is offline Offline
Newbie Poster
 
0
  #3
Oct 8th, 2009
Originally Posted by jlm699 View Post
Mensa: your code was very well structured and a nice example of reading user input then using it for calculation. Here's how I've modified your code:
  1. def calc_payment(int_rate, num_pmnts, principal, freq):
  2. ''' This function will calculate the payment amount of a loan.
  3. @ Inputs
  4. - int_rate - The interest rate of the loan
  5. - num_pmnts - The number of payments required
  6. - principal - The original amount of the loan (minus down-payment)
  7. - freq - Frequency of payments (weekly, monthly, quarterly, annually)
  8.  
  9. @ Returns
  10. - pmnt_amt - The amount that each payment will be
  11. '''
  12.  
  13. freq_lookup = {'weekly':52, 'monthly':12, 'quarterly':4, 'annually':1}
  14. int_rate = float(int_rate) / 100
  15.  
  16. rr = int_rate / freq_lookup[freq]
  17. x = (1.0 + rr) ** num_pmnts
  18. y = rr / (x - 1.0)
  19. pmnt_amt = (rr + y) * principal
  20.  
  21. return pmnt_amt
  22.  
  23.  
  24. def main():
  25. r = input('What is your interest rate? ')
  26. t = input('How many payments will you make? ')
  27. la = input('What was the amount of the loan? ')
  28. rt = None
  29. while rt not in ['weekly', 'monthly', 'quarterly', 'annually']:
  30. if rt:
  31. rt = raw_input('Sorry that was not an option, please respond with weekly, monthly, quarterly, or annually: ').lower()
  32. else:
  33. rt = raw_input('Do you make your payments weekly, monthly, quarterly, or annually? ').lower()
  34. payment = calc_payment(r, t, la, rt)
  35. print 'Your %s payment will be %.2f' % (rt, payment)
  36.  
  37.  
  38. if __name__ == '__main__':
  39. main()
  40. raw_input('Press Enter to Exit...')
Here are the modifications I made:

1. Moved the payment calculation to a function called calc_payment and added comments explaining what the function does, what inputs it expects and what the output means (this is something that you should get in the habit of doing, as it will help in the future and is good coding practice).

2. I removed the r = r + .0 line and instead consolidated it with the line immediately below it using the built-in float function (which converts the number to floating point, as does adding .0).

3. I added a dictionary lookup for the payment frequency. Each key is the word description that you ask the user for (weekly, monthly, quarterly, annually) and then the value corresponding to each key is the frequency that you were using in the calculations (52, 12, 4, 1 respectively). This allows us to use one calculation instead of doing four and then picking one of the results later.

4. Moved the user input requesting into the "main" function. Also added a statement that you'll see quite frequently when working with Python: if __name__ == '__main__': . This is typically the only statement that is not inside of a function (aside from a main function call or some initialization stuff, which are inside this "if" block). This statement makes sure that the program is running as the 'main' script, and executes accordingly. So now, if another program were to input <script_name> where script_name is the name of this script, that other program would not automatically run the main function and ask the user for input. Then your 'main' program would be able to call <script_name>.calc_payment and make use of it however you'd like.

5. Moved the part that tells the user they provided an incorrect input for frequency to where we get the input. This makes sure we don't do the calculation until the user has given us a correct input. I also used lower to make sure the string is all lower case and a list to validate and make sure their input is kosher.

I think that's about it, but if you have any questions about my modifications, please feel free to ask for further details!
Thanks! I got into Python just recently when I saw projecteuler.net and thought I'd give it a shot. I've only just messed with C and Java but Python seems easier for me to get the syntax of at first. Seeing an explanation and example of how my code could be made to be smoother is really helpful, thanks again!
Reply With Quote Quick reply to this message  
Join Date: Oct 2009
Posts: 17
Reputation: Mensa180 is an unknown quantity at this point 
Solved Threads: 1
Mensa180 Mensa180 is offline Offline
Newbie Poster
 
0
  #4
Oct 8th, 2009
OK I have a small question. What do %s and %.2f stand for? It looks like %s stands for freq and %.2f is the amount given by calc_payment(...).

Also I'm still trying to grasp the _name_ ==' _main_': concept.

Other than that I pretty much understand what you did! Not bad for a 17 year old!? Now I just need to think of another exercise where I can experiment in defining and using functions.
Reply With Quote Quick reply to this message  
Join Date: Oct 2008
Posts: 60
Reputation: HiHe is an unknown quantity at this point 
Solved Threads: 4
HiHe's Avatar
HiHe HiHe is offline Offline
Junior Poster in Training
 
0
  #5
Oct 8th, 2009
If you are familiar with C and its printf() function then you can use %s for strings and %0.2f for floats with 2 decimals. In Python like in Ruby you can use %s also for unformatted numbers.

In Ruby (much like C):
  1. printf( "Number: %5.2f, String: %s\n", 1.23456, "hello" )
  2. printf( "Number: %s, String: %s\n", 1.23456, "hello" )
In Python:
  1. print( "Number: %5.2f, String: %s\n" % ( 1.23456, "hello" ) )
  2. print( "Number: %s, String: %s\n" % ( 1.23456, "hello" ) )
In either case the output is:
  1. Number: 1.23, String: hello
  2. Number: 1.23456, String: hello
Last edited by HiHe; Oct 8th, 2009 at 6:37 pm. Reason: code
In C you can code our own bugs, in C++ you can inherit them.
Reply With Quote Quick reply to this message  
Join Date: Oct 2009
Posts: 17
Reputation: Mensa180 is an unknown quantity at this point 
Solved Threads: 1
Mensa180 Mensa180 is offline Offline
Newbie Poster
 
0
  #6
Oct 8th, 2009
Doh! I get it now, thanks, I missed the end of the line where it specified where it got the vars from. That explains why it didn't make sense to me.

print 'Your %s payment will be %.2f' % (rt, payment)
Last edited by Mensa180; Oct 8th, 2009 at 9:07 pm.
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 4,135
Reputation: vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice 
Solved Threads: 946
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite
 
0
  #7
Oct 9th, 2009
Just keep asking, we are all more than willing to help a sprouting Python talent.
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Oct 2009
Posts: 17
Reputation: Mensa180 is an unknown quantity at this point 
Solved Threads: 1
Mensa180 Mensa180 is offline Offline
Newbie Poster
 
0
  #8
Oct 10th, 2009
Just upgraded to Python 3.1.1, I think I was using 2.6. Apparently you now have to use parenthesis instead of just telling it what you want to print.

print 'Hello Python'
vs

print ('Hello Python')
I'm not sure what they've done with raw_input() , does plain old input() have the same functionality now? I will have to google the changes.

For now I am trying to figure out how to use functions with one another effectively.

  1. def mpg():
  2. travel = input('How many miles have you traveled? ')
  3. gallons = input('How many gallons of fuel did you use? ')
  4. mpg = float(travel) / float(gallons)
  5. print ('You get', mpg, 'miles per gallon.')
  6.  
  7. def mpt():
  8. mpg = input('How many miles per gallon does your vehicle get? ')
  9. tanksize = input('How large is your gas tank? ')
  10. tankmiles = float(tanksize) * float(mpg)
  11. print ('You will get', tankmiles, 'miles on a tank of fuel.' )

For example I am trying to use mpt(mpg()) to determine miles per tank without the user knowing at first what their mpg is. I have been on the road for most the day so I have not yet had a chance to research how to do things like this more thoroughly.
Last edited by Mensa180; Oct 10th, 2009 at 1:48 am.
Reply With Quote Quick reply to this message  
Join Date: Jul 2008
Posts: 1,067
Reputation: jlm699 is a jewel in the rough jlm699 is a jewel in the rough jlm699 is a jewel in the rough jlm699 is a jewel in the rough 
Solved Threads: 267
Sponsor
jlm699's Avatar
jlm699 jlm699 is offline Offline
Knows where his Towel is
 
0
  #9
Oct 10th, 2009
Originally Posted by Mensa180 View Post
I will have to google the changes.
Here you go: http://docs.python.org/dev/3.0/whatsnew/3.0.html

This gives a nice breakdown of the changes between 2.X and 3.X versions of Python. Hope it helps!
1. Use Code Tags.
2. Homework? Show Effort.
3. Keep discussions on the forum: no PMs
Reply With Quote Quick reply to this message  
Join Date: Oct 2009
Posts: 17
Reputation: Mensa180 is an unknown quantity at this point 
Solved Threads: 1
Mensa180 Mensa180 is offline Offline
Newbie Poster
 
0
  #10
Oct 10th, 2009
Thanks! I am on the road and thus without internet for long periods of time so sometimes I just have to sit frustrated wondering why a bit of code won't work now when it did before .

I'm not sure why this keeps giving me "Guess again!" though. Even though it is simple addition I made it print the answer to make sure there was no possibility of me getting it wrong, it worked in 2.6 and I thought the logic was fairly straightforward.

  1. from random import randint
  2. a = randint (1,10,)
  3. b = randint (1,10,)
  4. z = a + b
  5. print (z)
  6. print (a, "+", b, "=")
  7.  
  8. y = input('What is the answer? ')
  9.  
  10. control = True
  11.  
  12. while control:
  13. if y == z:
  14. print ('Correct!')
  15. control = False
  16. while y != z:
  17. y = input('Guess again! ')

I read through that doc and tried changing input() to eval(input()) but that just gave me parsing errors.

I hope this is one of those things I can come back to in 20 minutes and catch immediately, but so far I'm still looking.
Last edited by Mensa180; Oct 10th, 2009 at 11:35 am.
Reply With Quote Quick reply to this message  
Reply

This thread has been marked solved.
Perhaps start a new thread instead?
Message:



Similar Threads
Other Threads in the Python Forum


Views: 507 | Replies: 11
Thread Tools Search this Thread



Tag cloud for Python
About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC