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行移出for-loop:

for i in range(10):
    principal = principal * (1 + apr)
print "The value in 10 years is:", principal 
于 2013-06-10T14:27:09.723 回答
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 回答
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 回答