0

明確な範囲で最後の値を出力する方法は?

def main():
 print "This program calculates the future value of a 10-year investment."

 principal = input("Enter the initial principle: ")
 apr = input("Enter the annual interest rate: ")

 for i in range(10):
  principal = principal * (1 + apr)
  print "The value in 10 years is:", principal 

出力:

The value in 10 years is XXXXXXX
The value in 10 years is XXXXXXX
The value in 10 years is XXXXXXX
The value in 10 years is XXXXXXX
The value in 10 years is XXXXXXX
The value in 10 years is XXXXXXX
The value in 10 years is XXXXXXX
The value in 10 years is XXXXXXX
The value in 10 years is XXXXXXX
The value in 10 years is XXXXXXX

ループの最後の繰り返しだけを印刷するにはどうすればよいですか?

4

4 に答える 4

6

最後の行のインデントを解除します (インデントに 1 スペースを使用しないでください。PEP -8では 4 スペースを推奨しています)

def main():
    print "This program calculates the future value of a 10-year investment."

    principal = input("Enter the initial principle: ")
    apr = input("Enter the annual interest rate: ")

    for i in range(10):
        principal = principal * (1 + apr)
    print "The value in 10 years is:", principal 
于 2013-06-10T14:27:06.297 に答える
1

print-loopの外に行を移動するだけforです:

for i in range(10):
    principal = principal * (1 + apr)
print "The value in 10 years is:", principal 
于 2013-06-10T14:27:09.723 に答える
1
    with open("story.txt",encoding="utf-8") as f:
        for line in f:
            for word in line.split()
                aList.append( word )
        print(aList)
于 2016-03-09T13:13:46.000 に答える
1
def main():
    print "This program calculates the future value of a 10-year investment."
    principal = input("Enter the initial principle: ")
    apr = input("Enter the annual interest rate: ")
    for i in range(10):
        principal *= (1 + apr)
        print "The value in {0} years is: {1}".format(i + 1, principal)

本当に 10 年の値だけに関心がある場合は、for ループを次のように置き換えます。

print "The value in 10 years is:", principal * (1 + apr) ** 10
于 2013-06-10T14:44:04.193 に答える