简体   繁体   中英

How to get sum of outputs in for loop

I need the sum of all the outputs of Dm, but cannot use sum because it is not iterable. How do I go about getting the sum of all outputs?

def diff_calc():
    # create alias for all parsed arguments for cleaner code

    loan_type = args.type
    payment = args.payment
    principal = args.Principal
    periods = args.periods
    interest = args.interest

    if args.interest is None:
        interest = 10
    if args.Principal is None:
        principal = 1000000
    if args.periods is None:
        periods = 10

    i = (interest / (12 * 100))
    for m in range(1, periods + 1, 1):
            Dm = ((principal / periods) + i * (principal - (principal * (m - 1)) / periods))
            print(f'Month {m}: payment is {math.ceil(Dm)}')

Output is:

  • Month 1: payment is 108334
  • Month 2: payment is 107500
  • Month 3: payment is 106667
  • Month 4: payment is 105834
  • Month 5: payment is 105000
  • Month 6: payment is 104167
  • Month 7: payment is 103334
  • Month 8: payment is 102500
  • Month 9: payment is 101667
  • Month 10: payment is 100834

I need to add those number up and subtract my principal from that for the overpayment amount.

You can either store those values in a dictionary, and then manipulate it however you want:

monthly_payments = {}

for m in range(periods):
        Dm = some_calculation...
        monthly_payments['month_' + str(m)] = Dm

yearly_payments = sum(monthly_payments.value())

You can also just add each calculation of Dm to some variable to hold the total sum.

total = 0
for m in range(periods):
        Dm = some_calculation...
        total += Dm

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM