假设您以120美元的价格购买了一件家具,并且您将在未来的12个月内付款而无需付款。我正在尝试制作一个程序,告诉您未来12个月的每月付款情况。我制作的节目告诉你第一个月的每月付款/金额,但它只复制了所有12个月的第一个月,我想知道是否有人可以引导我朝着正确的方向,所以应付金额是正确的12个月。我知道我弄乱了某种方程式,但无法想出它。我在python上仍然很新,遇到了一些麻烦。这就是我所做的:
purchasePrice = input("Enter purchase price")
purchasePrice = int(purchasePrice)
month = 1
while month <=12:
print (month)
month = month + 1
monthlyPayment = purchasePrice/12
amountDue = purchasePrice - monthlyPayment
print ("Monthly payment", monthlyPayment)
print ("Amount due: ", amountDue)
我的输出是:
Enter purchase price 120
1
Monthly payment 10.0
Amount due: 110.0
2
Monthly payment 10.0
Amount due: 110.0
3
Monthly payment 10.0
Amount due: 110.0
4
Monthly payment 10.0
Amount due: 110.0
直到第12个月
答案 0 :(得分:0)
问题是每次这条线都符文 amountDue = purchasePrice - monthlyPayment purchasePrice = 120和monthlyPayment = 10因此amountDue不会改变。 您需要将月份乘以monthlyPayment,以查看您已支付每月付款的次数。并改变行的顺序,因为月份已经等于1.所以你的代码看起来像
purchasePrice = input("Enter purchase price")
purchasePrice = int(purchasePrice)
month = 1
while month <=12:
print (month)
monthlyPayment = purchasePrice/12
amountDue = purchasePrice - monthlyPayment * month
month = month + 1
print ("Monthly payment", monthlyPayment)
print ("Amount due: ", amountDue)
答案 1 :(得分:0)
您有多个在循环内声明的变量。当你在循环中声明一个变量时,它会被破坏并覆盖循环的每次迭代。您希望声明循环的变量OUTSIDE以保留每次迭代的变量。
##Condensed two lines into one.
purchasePrice = int(input("Enter purchase price"))
#Variable declaration for preservation.
monthlyPayment = purchasePrice/12
##Changing from a while loop to a for loop lets us remove the month variable
for x in range(1, 13)
print (x)
print ("Monthly payment", monthlyPayment)
##Here we get rid of the amountDue variable and just perform the calculation in the output
print ("Amount due: ", purchasePrice -((purchasePrice/12)*x))
现在基本表单正常工作,我们可以将代码压缩成更干净,代码更少的代码。
修订清洁表格:
{{1}}