Python:用于带有计数器和计划增量的循环



Python学习者。处理每月定期存款,利息问题。除了在这个假设中,我被要求在每6个月后加薪。我在不到几个月的时间里就达到了目标。

当前使用%函数和+=函数

annual_salary = float(input("What is your expected Income? "))                  
portion_saved = float(input("What percentage of your income you expect to save? "))
total_cost = float(input("what is the cost of your dream home? "))
semi_annual_raise = float(input("Enter your expected raise, as a decimal "))
monthly_salary = float(annual_salary/12)
monthly_savings = monthly_salary * portion_saved
down_payment= total_cost*.25

savings = 0
for i in range(300):
savings = monthly_savings*(((1+.04/12)**i) - 1)/(.04/12)
if float(savings) >= down_payment:
break
if i % 6 == 0 :
monthly_salary += monthly_salary * .03
monthly_savings = monthly_salary * portion_saved

谢谢大家的建议。我的代码越来越清晰,并且达到了正确的输出!问题在于我如何以及何时计算利息。在静态供款的情况下,我成功地使用了经常性存款的利息公式,在这里,需要更简单的每月利息计算方法来处理循环的流程。

annual_salary = float(input("What is your expected Income? "))                  
portion_saved = float(input("What percentage of your income you expect to save? "))
total_cost = float(input("what is the cost of your dream home? "))
semi_annual_raise = float(input("Enter your expected raise, as a decimal "))
monthly_salary = float(annual_salary/12)
monthly_savings = monthly_salary * portion_saved
down_payment = total_cost*.25
savings = 0
month = 1
while savings < down_payment :
print(savings)
savings += monthly_savings
savings = savings * (1+(.04/12))
month += 1  
if month % 6 == 0 :
monthly_salary += (monthly_salary * semi_annual_raise)
monthly_savings = (monthly_salary * portion_saved)
print("")
print("it will take " + str(month) + " months to meet your savings goal.")

这样的东西对你有用吗?通常,当我们不知道循环最终需要多少迭代时,我们希望使用while循环而不是for循环。

monthly_savings = 1.1 # saving 10% each month
monthly_salary = 5000
down_payment = 2500
interest = .02
savings = 0
months = 0
while savings < goal:
print(savings)
savings = (monthly_salary * monthly_savings) + (savings * interest)
months += 1

if months % 6 == 0 :
monthly_salary += monthly_salary * .03

print("Took " + str(months) + " to save enough")

最新更新