简单的for循环和打印

nut*_*hip -1 python for-loop

我在使用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个步骤一个接一个地打印.

我该如何解决这个问题?

小智 8

Python是缩进敏感的; 也就是说,它使用文本块的缩进级别来确定循环内部的代码行(例如,而不是{}大括号).

因此,为了将print语句移出循环(如上一个答案),只需减少缩进


Tom*_*ese 7

您可以将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的值(仅一次).