Erick Kangethe
Erick Kangethe

Reputation: 1

How to find sum of integers generated in a while loop

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

Above is what I have I would like to print the sum of yes after the loop is done, I tried y = yes += yes print(y) this didn't work

Upvotes: 0

Views: 60

Answers (4)

ztindall
ztindall

Reputation: 54

I think I would use list comprehension combined with a function:

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)

Upvotes: 0

gosuto
gosuto

Reputation: 5741

If you set yes to zero before the loop you can just += it:

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

Upvotes: 1

C.Nivs
C.Nivs

Reputation: 13106

This could be better accomplished in a for loop rather than a 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)

Upvotes: 0

Gaurang Shah
Gaurang Shah

Reputation: 12920

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

Upvotes: 1

Related Questions