我在使用Python 2.7
我正在做一些非常基本的练习,这是我的代码:
def main():
print """Program computes the value of an investment
carried 10 years into the future"""
principal = input("Enter the principal: ")
apr = input("Provide (in decimal format) the annual percentage rate: ")
for i in range(10):
principal = principal * (1 + apr)
print "The value in 10 years will be: $", principal
main()
Run Code Online (Sandbox Code Playgroud)
代码正在运行,但我希望输出只是最终结果.我现在得到的是循环的所有10个步骤一个接一个地打印.
我该如何解决这个问题?
您可以将print语句移出循环:
for i in range(10):
principal = principal * (1 + apr)
print "The value in 10 years will be: $", principal
Run Code Online (Sandbox Code Playgroud)
这意味着在for循环中计算principal的值,然后在for循环之外打印principal的值(仅一次).