如何查找在while循环中生成的整数和

时间:2019-03-18 19:00:40

标签: python while-loop sum

salary = 1000
interest = 0.002 * salary
x = 0
while x < 12:
    yes = 0.15 * salary
    salary += interest
    x += 1

以上是我所拥有的 我想在循环完成后打印yes的总和,我试过了 y =是+ =是 打印(y)这不起作用

4 个答案:

答案 0 :(得分:1)

salary = 1000
interest = 0.002 * salary
x = 0
sum_of_yes=0
while x < 12:
    yes = 0.15 * salary
    salary += interest
    x += 1
    sum_of_yes+=yes

print sum_of_yes

答案 1 :(得分:1)

如果在循环之前将yes设置为零,则可以+=进行设置:

salary = 1000
interest = 0.002 * salary
x = 0
yes = 0
while x < 12:
    yes += 0.15 * salary
    salary += interest
    x += 1
print(yes)

答案 2 :(得分:0)

通过for循环而不是while可以更好地实现:

salary = 1000
interest = .002 * salary
x, total_yes = 0, 0

# This will keep track of x for you
for x in range(12):
    yes = 0.15 * salary
    salary += interest
    total_yes += yes

print(total_yes)

答案 3 :(得分:0)

我想我将结合使用列表理解和功能:

salary = 1000
interest = 0.002

def sum_yes(salary, interest):
    monthly_interest = 0.002 * salary
    monthly_salaries = [salary + (monthly_interest * month) for month in range(12)]
    return sum([month_salary * 0.15 for month_salary in monthly_salaries])

yes = sum_yes(salary, interest)
print(yes)