[Tutor] python strings?

Daniel Watkins daniel at thewatkins.org.uk
Thu Sep 8 18:39:21 CEST 2005


On Thu, 2005-09-08 at 15:15 +0100, andrade1 at umbc.edu wrote:
>     for i in range(10): 
>         principal = principal * (1 + apr)
To calculate compound interest, you in fact don't need to use a loop at
all (you could use: 'final = principal * (apr ** years)') but if you
really want to use a loop, I would use a while loop (although this may
not be the best way involving loops, my loop-fu isn't great).
The while loop would look like:
	while years:
		principal = principal * (1 + apr)
		years = years - 1
If you planned to use fractions of years, then you need to tweak this.

>     print "The value in years is", principal
To actually answer your question, in order to print this correctly, you
need to tell Python to convert the integer (principal) to a string by
using the built-in function str() like so:
	print "The value in years is", str(principal)

To include the years, you would just add 'str(years)' in an appropriate
position, although if you've used the while loop, then referring to
years will simply give you 0, as you've been adjusting it. The solution
to this is to assign 'years' to a different variable initially (and use
one in the loop and the other here) in order to preserve it.



More information about the Tutor mailing list