我试图让while
循环运行dur
次,但是当我运行它只是坐在那里,我假设计算,似乎永远。这是一个简单的脚本,不需要很长时间才能运行,因此我假设我已经弄乱了while
循环。
这是代码: #Compound兴趣计算器
print "Enter amounts without $, years or %"
loan = input("How many dollars is your loan? ")
dur = input("How many years is your loan for? ")
per = input("What percent is the interest on your loan? ")
percent = per / 100
count = 0
#First calculation of amount
first = loan * percent
count = count + 1
#Continued calculation occurs until count is equal to the duration set by the user
while count <= dur:
out = first * percent
#Prints output
output = out + loan
print str(output)
答案 0 :(得分:2)
您的代码存在许多问题。
percent
始终为0
,因为您使用的是整数除法。请改为percent = per / 100.0
。count
来结束循环。first
和percent
,out
的计算值在循环的每次迭代中都是相同的。请改为first = first * percent
。最后,你根本不需要循环。就这样做:
output = loan * (1 + per/100.)**dur
答案 1 :(得分:1)
您需要在while循环中增加count
,否则停止条件(count <= dur
)将永远不会发生。
while count <= dur:
# do something
count += 1
如果您事先知道要做某事的次数,您也可以使用:
for i in xrange(dur): # use range if python3
# do something
另请注意,您的代码还有另一个问题:您并未真正计算复合兴趣。在每一步中,您都需要重新计算first * percent
,而不是将percent
添加到之前的兴趣中。你应该这样做:
# First calculation of amount
out = loan * percent
count = count + 1
while count <= dur:
out *= (1.0 + percent)
count += 1
答案 2 :(得分:0)
count
永远不会在循环中发生变化。这样做
while count <= dur:
out = first * percent
count += 1