you're overwriting k
at each iteration, so in the end the result is just (5*8+17)*2
To perform such a sum, with x varying between 3 and 8 (9 is not included) so it in a generator comprehension and pass the result to sum
, you'll avoid the nasty side-effects like you just created.
result = sum(5*x+17 for x in range(3,9))
(of course if you want to include 9
you have to range from 3
to 10
), so depending on the upper boundary, you get 267
or 329
You can also do that without using sum
at all using the n*(n+1)//2
formula for sum of integers from 1 to n and adapting it a la project euler to reduce complexity:
start = 3
end = 9 # inclusive
result = ((end*(end+1))//2 - ((start-1)*(start))//2)*5 + (end-start+1)*17