Python 根据利息、原则和使用年限计算总金额

Python 根据利息、原则和使用年限计算总金额,python,for-loop,Python,For Loop,我正在尝试创建一个程序,询问用户他们的本金、利率和年总金额。我想让我的计划向他们展示他们每年预期的总回报额。我想从第一年开始。当我运行脚本时,它只显示了一年的总兴趣。这是我到目前为止所拥有的 #Declare the necessary variables. princ = 0 interest = 0.0 totYears = 0 year = 1 #Get the amont of principal invested. print("Enter the principal amount.

我正在尝试创建一个程序,询问用户他们的本金、利率和年总金额。我想让我的计划向他们展示他们每年预期的总回报额。我想从第一年开始。当我运行脚本时,它只显示了一年的总兴趣。这是我到目前为止所拥有的

#Declare the necessary variables.
princ = 0
interest = 0.0
totYears = 0
year = 1

#Get the amont of principal invested.
print("Enter the principal amount.")
princ = int(input())

#Get the interest rate being applied.
print("Enter the interest rate.")
interest = float(input())

#Get the total amount of years principal is invested.
print ("Enter the total number of years you're investing this amonut.")
totYears = int(input())

for years in range(1, totYears):
    total=year*interest*princ
    years += 1

print (total)

非常感谢您的帮助。

这里有问题:

for years in range(1, totYears):
    total=year*interest*princ
    years += 1

print (total)
  • 您可以在循环中更改年。不要。for语句为您解决了这一问题。你的干扰使在循环中每次变化2
  • 每次通过循环,你都会扔掉上一年的利息,然后计算一个新的利息。您的print语句在循环之外,因此只打印total的最终值
  • 您的循环指数是,但您已经计算了变量,该变量始终为1。我多年前学会的一种编程技巧是永远不要使用复数变量名
  • 也许你需要这个:

    for years in range(1, totYears):
        total = years * interest * princ
        print (total)
    

    谢谢,这澄清了问题。然而,我怎样才能让它像表格一样显示每年的应计利息呢。例如,第1年=500年,第2年=1000年,第3年=2000年,等等。我的显示了总年数的最终利息,并重复了四次。将打印语句放入循环中,就像我在上面的最后一段代码中显示的那样。根据我的范围(totYears),totYears不应该从第1年及以上开始吗?例如,当我输入totYears为5时,它从5到10年开始计算。如何修复此问题?否。年份从1年到(但不包括)年。您发布的代码(以及我的更新)都运行1到4。我不知道为什么它运行5到10;您尚未发布该代码。谢谢,我应该澄清代码并保持一致。我只是改变了你给我的一些建议。我不知道如何将更新后的代码作为注释发布。所以我要么回答下面的问题,要么创建一个新问题。对不起,我对这件事还不熟悉。干杯请停止将问题更新和新问题作为答案发布!将它们编辑到问题正文中,或作为单独的问题发布。我很抱歉!这是我第一次用这个。我将作为新问题发回。我试图采纳你的建议,但我仍然拥有从5开始的年度计数器(或你为今年选择的任何值)。