Connecting Tech Pros Worldwide Help | Site Map

hi i have got a problem writing the code for this program

Newbie
 
Join Date: Aug 2009
Posts: 2
#1: Aug 18 '09
this is the program as below and now what i need to do is add the following to it but i am not able to get how to do it
Expand|Select|Wrap|Line Numbers
  1. # futval.py
  2. #    A program to compute the value of an investment
  3. #    carried 10 years into the future
  4.  
  5. def main():
  6.     print "This program calculates the future value"
  7.     print "of a 10 year investment."
  8.  
  9.     principal = input("Enter the initial principal: ")
  10.     apr = input("Enter the annualized interest rate: ")
  11.  
  12.     for i in range(10):
  13.         principal = principal * (1 + apr)
  14.  
  15.     print "The value in 10 years is:", principal
  16.  
  17. main()
the output i get is

This program calculates the future value
of a 10 year investment.
Enter the initial principal: 1000
Enter the annualized interest rate: .1
The value in 10 years is: 2593.7424601

but i need to get an output like this as below

This program calculates the future value
of a 10 year investment.
Enter the initial principal: 1000
Enter the annualised interest rate: .1
Year Value
----------------
0 1100.00
1 1210.00
2 1331.00
3 1464.10
4 1610.51
5 1771.56
6 1948.72
7 2143.59
8 2357.95
9 2593.74
The value in 10 years is: 2593.74

so i would be thankful if anybody could help me out as i am new to python
bvdet's Avatar
Moderator
 
Join Date: Oct 2006
Location: Nashville, TN
Posts: 1,563
#2: Aug 18 '09

re: hi i have got a problem writing the code for this program


This can be done with string formatting, Look here under "6.6.2. String Formatting Operations" for documentation. I will post again with an example.

-BV
bvdet's Avatar
Moderator
 
Join Date: Oct 2006
Location: Nashville, TN
Posts: 1,563
#3: Aug 18 '09

re: hi i have got a problem writing the code for this program


Print the table header:
Expand|Select|Wrap|Line Numbers
  1. >>> print "%-5s%s" % ("Year", "Value")
  2. Year Value
You can use string methods also:
Expand|Select|Wrap|Line Numbers
  1. >>> print "%s%s" % ("Year".center(6), "Value".center(8))
  2.  Year  Value  
Print the separator:
Expand|Select|Wrap|Line Numbers
  1. >>> print '-'*14
  2. --------------
Inside the for loop, print the intermediate results. Example:
Expand|Select|Wrap|Line Numbers
  1. >>> p = 10
  2. >>> for i in range(10):
  3. ...     print "%-5s%.2f" % (i, p)
  4. ...     p *= 2
  5. ...     
  6. 0    10.00
  7. 1    20.00
  8. 2    40.00
  9. 3    80.00
  10. 4    160.00
  11. 5    320.00
  12. 6    640.00
  13. 7    1280.00
  14. 8    2560.00
  15. 9    5120.00
  16. >>> 
Reply