Python - 获取while循环运行一定次数

时间:2014-02-25 09:41:29

标签: python python-2.7 while-loop

我试图让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)

3 个答案:

答案 0 :(得分:2)

您的代码存在许多问题。

  1. percent始终为0,因为您使用的是整数除法。请改为percent = per / 100.0
  2. 正如其他人所说,你必须增加count来结束循环。
  3. 在循环中不更改firstpercentout的计算值在循环的每次迭代中都是相同的。请改为first = first * percent
  4. 最后,你根本不需要循环。就这样做:

    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