[Tutor] python strings?
Oliver Maunder
olivermaunder at gmail.com
Thu Sep 8 20:31:27 CEST 2005
On 08/09/05, andrade1 at umbc.edu <andrade1 at umbc.edu> wrote:
>
> below is my program. what i would like to do is to get the last line to
> print the number of years that the user enters and also the principal
There are a couple (at least!) of ways to get the values into the string
that you print.
The first way is to pass several values to the print command:
print "The value in", years, "is", principal
Another way is to use placeholders:
print "The value in %d years is %.2f" % (years, principal)
The placeholders (shown by the % sign) get replaced by the variables in the
list, in order. "%d" means format the value as an integer. "%.2f" means
format it as a floating point value with two decimal places. See
http://diveintopython.org/native_data_types/formatting_strings.html for more
details.
You could replace the main bit of the program with a single line, if you're
feeling brave!
principal = input("Enter the initial principal: ")
apr = input("Enter the annual interest rate: ")
years = input("Enter the number of years: ")
print "The value in %d years will be %.2f" % (years, principal * (1 +
apr)**years)
Hope this is useful!
Olly
# A program to compute the value of an investment
> # years into the future
>
> def main():
> print "This program calculates the future value of an investment over
> years"
>
> principal = input("Enter the initial principal: ")
> apr = input("Enter the annual interest rate: ")
> years = input("Enter the number of years: ")
>
> for i in range(10):
> principal = principal * (1 + apr)
>
> print "The value in years is", principal
>
> main()
>
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050908/b45c1b56/attachment.htm
More information about the Tutor
mailing list