每月付款使用for循环

时间:2017-01-07 17:14:19

标签: python

我是Python的新手,我正在尝试创建一个程序,让我可以继续每月添加12个月的付款。这就是我到目前为止所做的:

for i in range(1,13):     
   print('this is month',i)     
   add = int(input('how much money do you want to add?: '))     
   print(add)

请保持代码简单。感谢。

2 个答案:

答案 0 :(得分:0)

有几种方法可以做到这一点:

  1. 就地添加

    # start with zero dollars paid at month 1
    add = 0 
    for i in range(1,13):     
        print('this is month',i)     
        month_add = int(input('how much money do you want to add?: '))
        add += month_add
    
    print(add)
    
  2. 变量重新分配:

    add = 0
    for i in range(1,13):     
        print('this is month',i)     
        month_add = int(input('how much money do you want to add?: '))
        add = add + month_add
    
    print(add)
    
  3. 最后使用listsum跟踪每个月的付款:

    # initialize the monthly payment list
    monthly_payments = []
    for i in range(1,13):     
        print('this is month',i)     
        add = int(input('how much money do you want to add?: '))
        monthly_payments.append(add)
    
    total_paid = sum(monthly_payments)
    print(total_paid)
    
  4. 使用字典跟踪每个月的付款:

    monthly_payments = {}
    for i in range(1,13):     
        print('this is month',i)     
        add = int(input('how much money do you want to add?: '))
        monthly_payments[i] = add
    
    total_paid = sum(amount for month, amount in monthly_payments.items())
    print(total_paid)
    

答案 1 :(得分:-1)

简单!

add = 0
for i in range(1,13):     
   print('this is month',i)     
   add += int(input('how much money do you want to add?: '))     
   print(add)