猿问

仅在确定循环中打印最后一个值

如何打印确定范围内的最后一个值?


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

如何仅打印循环的最后一次迭代?


大话西游666
浏览 173回答 3
3回答

绝地无双

取消最后一行的缩进(请不要再使用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 

慕勒3428872

只需将print行移出for-loop即可:for i in range(10):    principal = principal * (1 + apr)print "The value in 10 years is:", principal 

PIPIONE

  with open("story.txt",encoding="utf-8") as f:        for line in f:            for word in line.split()                aList.append( word )        print(aList)
随时随地看视频慕课网APP

相关分类

Python
我要回答