如何解决如何在python中使用两个条件循环?
我需要编写一个代码,显示0到20年或当今天的价值达到投资初始投资金额的.5 *时的投资回报。我被后者困住了。当我使用IF语句时,我什么也得不到。这是我的代码。
def getExpInvestAmt(investAmt,i,n):
expInvestAmt = int(investAmt * pow(1 + i / 100,n))
return expInvestAmt
def getPresentValue(exp_invest_amt,d,n):
adjAmt = int(exp_invest_amt / pow(1 + d / 100,n))
return adjAmt
def main():
investAmt = float(input("Enter investment amount:"))
i = float(input("Enter the expected investment growth rate:"))
d = float(input("Enter the discount rate:"))
n = 0
adjA = 0
print("Year \t Value at year($) \t Today's worth($)")
for x in range(0,21):
if adjA < 0.5 * investAmt
break
expected_value = getExpInvestAmt(investAmt,n)
present_value = getPresentValue(expected_value,n)
n += 1
adjA += 1
print("{} \t {:,} \t {:,}".format(x,expected_value,present_value))
main()
这就是我应该得到的,
Enter investment amount: 10000
Enter the expected investment growth rate: 5
Enter the discount rate: 6.25
Year Value at Year($) Today's worth($)
1 10,500 9,346
2 11,025 8,734
3 11,576 8,163
4 12,155 7,629
5 12,763 7,130
6 13,401 6,663
7 14,071 6,227
8 14,775 5,820
9 15,513 5,439
10 16,289 5,083
11 17,103 4,751 # today's value have reached <= 50% of the initial amount program stops.
解决方法
我认为您可以简化代码;您不需要adjA
或x
。在使用adjA
的地方,您应该只使用present_value
,并且可以在范围内迭代n
而不是x
:
def main():
investAmt = float(input("Enter investment amount:"))
i = float(input("Enter the expected investment growth rate:"))
d = float(input("Enter the discount rate:"))
print("Year \t Value at year($) \t Today's worth($)")
for n in range(1,21):
expected_value = getExpInvestAmt(investAmt,i,n)
present_value = getPresentValue(expected_value,d,n)
print("{} \t {:,} \t {:,}".format(n,expected_value,present_value))
if present_value < 0.5 * investAmt:
break
要获得investAmt
为10000和i
为5的预期结果,您需要d
的值为12.347528。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。