944,110 Members | Top Members by Rank

Ad:
  • Python Discussion Thread
  • Marked Solved
  • Views: 1484
  • Python RSS
You are currently viewing page 1 of this multi-page discussion thread
Oct 6th, 2009
1

loan calculator

Expand Post »
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.

Python Syntax (Toggle Plain Text)
  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
Similar Threads
Reputation Points: 13
Solved Threads: 7
Light Poster
Mensa180 is offline Offline
31 posts
since Oct 2009
Oct 7th, 2009
1
Re: loan calculator
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:
python Syntax (Toggle Plain Text)
  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!
Reputation Points: 355
Solved Threads: 292
Veteran Poster
jlm699 is offline Offline
1,102 posts
since Jul 2008
Oct 8th, 2009
0
Re: loan calculator
Click to Expand / Collapse  Quote originally posted by jlm699 ...
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:
python Syntax (Toggle Plain Text)
  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!
Reputation Points: 13
Solved Threads: 7
Light Poster
Mensa180 is offline Offline
31 posts
since Oct 2009
Oct 8th, 2009
0
Re: loan calculator
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.
Reputation Points: 13
Solved Threads: 7
Light Poster
Mensa180 is offline Offline
31 posts
since Oct 2009
Oct 8th, 2009
0
Re: loan calculator
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:
python Syntax (Toggle Plain Text)
  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:
Python Syntax (Toggle Plain Text)
  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
Reputation Points: 95
Solved Threads: 15
Junior Poster
HiHe is offline Offline
172 posts
since Oct 2008
Oct 8th, 2009
0
Re: loan calculator
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.
Reputation Points: 13
Solved Threads: 7
Light Poster
Mensa180 is offline Offline
31 posts
since Oct 2009
Oct 9th, 2009
0
Re: loan calculator
Just keep asking, we are all more than willing to help a sprouting Python talent.
Moderator
Reputation Points: 1333
Solved Threads: 1404
DaniWeb's Hypocrite
vegaseat is offline Offline
5,792 posts
since Oct 2004
Oct 10th, 2009
0
Re: loan calculator
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.

python Syntax (Toggle Plain Text)
  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.
Reputation Points: 13
Solved Threads: 7
Light Poster
Mensa180 is offline Offline
31 posts
since Oct 2009
Oct 10th, 2009
0
Re: loan calculator
Click to Expand / Collapse  Quote originally posted by Mensa180 ...
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!
Reputation Points: 355
Solved Threads: 292
Veteran Poster
jlm699 is offline Offline
1,102 posts
since Jul 2008
Oct 10th, 2009
0
Re: loan calculator
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.

python Syntax (Toggle Plain Text)
  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.
Reputation Points: 13
Solved Threads: 7
Light Poster
Mensa180 is offline Offline
31 posts
since Oct 2009

This thread is solved

Either the thread starter or a moderator has marked this thread as solved. You can most likely trust the responses and answers given. There is most likely no reason for any further responses to be posted here. If you have a related question, please start a new thread in this forum instead.

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in Python Forum Timeline: Help Checksum program..
Next Thread in Python Forum Timeline: Errno 10061 while trying to send a mail from script





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC