Python Forum

Full Version: Formatting question regarding tables (Interest loan calculator)
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
Hey guys I am pulling my hair out over this program. 

Basically; 

I am instructed to write a program that calculates the total amount of savings for 1 to 10 years with interest ranging from 2.00% to 5.50%. Also I am required to calculate the total savings made if initial investment was $100 initially using the following equation:

S = P (1 + i/n)

Where:
• S is the total savings made
• P is the initial value invested (set this to $100)
• j is the annual interest rate (set this to the interest rate / 100)
• n is the number of times that interest is compounded per year (this is monthly so set this value to 12)
• t is the number of years that money is saved for

Display the results. An example of the layout/formatting what my output SHOULD look like below:

**Savings on initial investment of $100.00**
Years:                            1               2               3                4                 5               6              7               8               9               10
interest rate: 2.00%      102.02      104.08      106.18       108.32        110.51      112.74     115.01      117.34      119.70      112.12
(This formula continues from 2.00% to 5:50%)


For some strange reason I seem to be off a couple decimal places with my output as I have been trying to get it to work all day. Its not in the correct format either which is something I am also stuck on

I have been given some hints too but I am a little confused as what they are portraying

Hints:
• line two of the header displaying the years can be created using a fixed string or another for-loop - whichever you prefer.
• tabs between the items of output can help in getting even spacing.
• get one for-loop (the one that creates a single row) working correctly, then wrap it in another for-loop, that creates new rows.
o e.g. you could have a variable called interest and set it to 2.00
o then use a single for-loop to create the first row of the table
o once this is going, take the for-loop statement and surround it with another for-loop that changes interest

Anyway 

Here is what I have so far. Sorry if the explanation is poor the instructions were confusing enough but if someone could point me in the right direction that would be awesome and much appreciated XD

import sys

if sys.hexversion < 0x3000000:
    rng = xrange
    inp = raw_input
else:
    rng = range
    inp = input

def getter_fn(datatype):
    if datatype == str:
        return inp
    else:
        def fn(prompt=''):
            while True:
                try:
                    return datatype(inp(prompt))
                except ValueError:
                    pass
        return fn

get_float = getter_fn(float)
get_int   = getter_fn(int)

def main():
    principal  = get_float("Initial investment amount? ")
    periods    = get_int  ("How many years")
    deposit    = get_float("Annual deposit amount? ")
    apr        = get_float("Annual interest rate (in percent)? ") / 100


    deposits    = [deposit] * periods
    no_deposits = [0.] * (- periods)

    amount = principal
    for yr, d in enumerate(deposits + no_deposits, 1):
        amount = (amount + d) * (1. + apr)
        print('After {:>2d} year{} you have:   $ {:>10.2f}'.format(yr, 's,' if yr > 1 else ', ', amount))

if __name__ == '__main__':
    main()
My output:

Initial investment amount? 100
How many years10
Annual deposit amount? 0
Annual interest rate (in percent)? 2.25
After  1 year,  you have:   $     102.25
After  2 years, you have:   $     104.55
After  3 years, you have:   $     106.90
After  4 years, you have:   $     109.31
After  5 years, you have:   $     111.77
After  6 years, you have:   $     114.28
After  7 years, you have:   $     116.85
After  8 years, you have:   $     119.48
After  9 years, you have:   $     122.17
After 10 years, you have:   $     124.92

Process finished with exit code 0
Thanks guys for any help really appreciate it in advance :)
OK, small hint:
header = ['Years:', '']
for y in range(1,11):
   header.append(str(y))
print '\t'.join(header)
Output:
Years:          1       2       3       4       5       6       7       8       9       10 >>>
(May-03-2017, 10:23 AM)buran Wrote: [ -> ]OK, small hint:
header = ['Years:', '']
for y in range(1,11):
   header.append(str(y))
print '\t'.join(header)
Output:
Years:          1       2       3       4       5       6       7       8       9       10 >>>

Thanks dude now its just a case of putting that in the right place haha also gives me a template on what to use for the user input and how to format that correctly too. Cheers I will get onto this before my brain turns to mush XD
Hey guys im really still quite stuck on this particular part

**Savings on initial investment of $100.00**
Years: 1 2 3 4 5 6 7 8 9 10
interest rate: 2.00% 102.02 104.08 106.18 108.32 110.51 112.74 115.01 117.34 119.70 112.12
(This formula continues from 2.00% to 5:50%)

I can get it to print in that format but adding the percentages up to 5.00% is driving me nuts
Hey everyone I just need to know how to allign my output in a row and snap it to a predefined list such as this also does anyone know how to get my output to round to 2 decimal places?

e.g

1          2           3           4           5   6   7   8   9   10
value1  value2   value3   value4    etc etc etc etc etc

So far my code looks like this

import sys

if sys.hexversion < 0x3000000:
    rng = xrange
    inp = raw_input
else:
    rng = range
    inp = input

def getter_fn(datatype):
    if datatype == str:
        return inp
    else:
        def fn(prompt=''):
            while True:
                try:
                    return datatype(inp(prompt))
                except ValueError:
                    pass
        return fn

get_float = getter_fn(float)
get_int   = getter_fn(int)

def main():
    principal  = get_float("Initial investment amount? ")
    apr        = get_float("Annual interest rate (in percent)? ") / 100
    header = ['Years:', '']
    for y in range(1,11):
        header.append(str(y))
    print ('\t'.join(header))

    amount = principal
    for y in range(1,11):
        amount = (amount) * (1. + apr)
        print (amount)
if __name__ == '__main__':
    main()
And my output is like this (just need to know how to allign the numbers to the years correct years 1 2 3 4 5....)

Initial investment amount? 100
Annual interest rate (in percent)? 2.25
Years: 1 2 3 4 5 6 7 8 9 10
102.25
104.550625
106.90301406249999
109.30833187890624
111.76776934618164
114.28254415647072
116.8539013999913
119.4831141814911
122.17148425057465
124.92034264621257

Process finished with exit code 0
Cheers in advance :)
I merged your threads together since... they're the same thing :p

Looks like you should look up string formatting, as that might solve all your remaining issues:
>>> val = 114.28254415647072
>>> print(val)
114.28254415647072
>>> print("{0:.2f}".format(val))
114.28
(May-04-2017, 08:39 PM)nilamo Wrote: [ -> ]I merged your threads together since... they're the same thing :p

Looks like you should look up string formatting, as that might solve all your remaining issues:
>>> val = 114.28254415647072
>>> print(val)
114.28254415647072
>>> print("{0:.2f}".format(val))
114.28

Thanks man I will check it out. been stuck on it for some time now XD

I keep coming across this error
    print ('\t'.join(amount))
TypeError: can only join an iterable
That's one amount.  str.join only works with an iterable, ie: multiple things.  So maybe format all your stuff, and THEN try printing it.
>>> import random
>>> vals = []
>>> for _ in range(5):
...   formatted = "{0:.2f}".format(100 * random.random())
...   vals.append(formatted)
...
>>> vals
['65.01', '23.51', '71.30', '72.77', '40.88']
>>> '\t'.join(vals)
'65.01\t23.51\t71.30\t72.77\t40.88'
>>> print('\t'.join(vals))
65.01   23.51   71.30   72.77   40.88
>>>
So if I want to make a table and allign the results in a row to something like years neatly what would I need to change 

years = print("Years\t 1 \t\t2\t\t3\t\t4\t\t5\t\t6\t\t7\t\t8\t\t9\t\t10")
print("-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_")
principal  = 100
rate = 2.00
intrst = (rate) / 100
amount = principal
for hours in range(10): #for each column
        amount = (amount) * (1. + intrst)
        print("\t\t{0:.2f}".format(amount))
Years 1 2 3 4 5 6 7 8 9 10
-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_
102.00
104.04
106.12
108.24
110.41
112.62
114.87
117.17
119.51
121.90

Process finished with exit code 0
By default, print() adds a newline character to the end of whatever you pass it.  If you use the end= parameter of print(), you can change that so it doesn't happen for you:

>>> for i in range(5):
...   print(i)
...
0
1
2
3
4
>>> for i in range(5):
...   print(i, end="")
...
01234>>>
Pages: 1 2