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
,否则停止条件(countcount
在循环中不会更改。请执行此操作
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