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

Python-获取while循环以运行一定的次数,python,python-2.7,while-loop,Python,Python 2.7,While Loop,我试图获得一个while循环来运行dur的次数,但是当我运行它时,它就停在那里,我假设它在计算,似乎永远在运行。这是一个简单的脚本,运行时间不应该太长,所以我假设我已经把while循环搞砸了 代码如下: #复利计算器 print "Enter amounts without $, years or %" loan = input("How many dollars is your loan? ") dur = input("How many years is your loan for? ")

我试图获得一个
while
循环来运行
dur
的次数,但是当我运行它时,它就停在那里,我假设它在计算,似乎永远在运行。这是一个简单的脚本,运行时间不应该太长,所以我假设我已经把
while
循环搞砸了

代码如下: #复利计算器

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)
print“输入不带美元、年份或%的金额”
loan=输入(“您的贷款是多少美元?”)
dur=输入(“您的贷款期限是多少年?”)
per=输入(“您的贷款利息是多少?”)
百分比=每100
计数=0
#金额的首次计算
第一=贷款*百分比
计数=计数+1
#继续计算,直到计数等于用户设置的持续时间

while count您需要在while循环中增加
count
,否则停止条件(
count
count
在循环中不会更改。请执行此操作

while count <= dur:
    out = first * percent
    count += 1

而count您的代码存在许多问题

  • percent
    将始终为
    0
    ,因为您使用的是整数除法。请尝试使用
    percent=per/100.0
  • 正如其他人所指出的,您必须增加
    count
    以结束循环
  • 如果不更改循环中的
    first
    percent
    ,则
    out
    的计算值在循环的每次迭代中都是相同的。请改为尝试
    first=first*percent
  • 最后,您根本不需要循环。只需执行以下操作:

    output = loan * (1 + per/100.)**dur
    

    您需要在
    while
    循环中增加count,否则它将永远不会退出。在
    while
    循环中添加:
    count=count+1
    。@isedev您是正确的,请使用
    out
    注意
    out
    在第一次迭代后的值与在第1000次迭代后的值完全相同,因为两者都不是
    first
    percent
    循环中的变化。谢谢!我才意识到它不是复合的。
    out*=percent
    这将使
    out
    在循环的每次迭代中越来越小。Thnaks,这工作得更好,但是你能解释一下
    1+
    的作用吗?我知道这是必要的,因为我试着用虽然没有,但我不太清楚它是做什么的。
    1+
    会变成例如
    0.03
    (3%)进入
    1.03
    ,因此您可以只计算
    loan*1.03
    ,而不是
    loan+loan*0.03
    。电力操作员
    **
    然后将其转换为
    loan*1.03*1.03*…*1.03
    @mm865如果这解决了您的问题,您可以“接受”这个答案(或者另一个,如果您更喜欢的话)将问题标记为已解决。
    # First calculation of amount
    out = loan * percent
    count = count + 1
    
    while count <= dur:
        out *= (1.0 + percent)
        count += 1
    
    while count <= dur:
        out = first * percent
        count += 1
    
    output = loan * (1 + per/100.)**dur