我是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)
请保持代码简单。感谢。
答案 0 :(得分:0)
有几种方法可以做到这一点:
就地添加
# 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)
变量重新分配:
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)
最后使用list
和sum
跟踪每个月的付款:
# 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)
使用字典跟踪每个月的付款:
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)