[SOLVED] For Loop not counting properly

Issue

The prompt for the exercise is as follows:

Uses a for loop to sum count values from start by increment.
Use: total = sum_count(start, increment, count)
Parameters:
start – the range start value (int)
increment – the range increment (int)
count – the number of values in the range (int)

What i’ve come up with:

def sum_count(start, increment, count):
    total = start
    for i in range(start, count):
        i += increment
        total += i
    else:
        return total

When i call and print the function using values 2, 2, 5, the return should be 30, however I am only returning a value of 17. Which part of my code is wrong?

Solution

If you want to repeat something x times, you can use a loop for _ in range(x) that doesn’t do anything with the value _ itself.

Reading the task as

Use a for loop to sum count values from start by increment

means that count is not the upper boundary of the range – that’s what you did – but the number of values to add up. So for count times, increase the start value by increment and take the sum of the values.

def sum_count(start, increment, count):
    total = 0
    
    for _ in range(count):
        total += start
        start += increment
   
    return total

Answered By – fsimonjetz

Answer Checked By – Katrina (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *