如何在一定范围内打印最后一个值?
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
如何只打印循环的最后一次迭代?
答案 0 :(得分: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
答案 1 :(得分:1)
只需将print
行移出for
- 循环:
for i in range(10):
principal = principal * (1 + apr)
print "The value in 10 years is:", principal
答案 2 :(得分: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
答案 3 :(得分:1)
with open("story.txt",encoding="utf-8") as f:
for line in f:
for word in line.split()
aList.append( word )
print(aList)