The other answer observes that some one character variable names can be confused. This can partly be avoided by choosing a better font in your editor (although O will always be problematic). Even then, you want to use more descriptive variable names. You went to the trouble to tell us about l
, k
, and m
. Why not just make those names a bit more descriptive? This might also help you notice that k
changes between your comments about k
and m
.
I don't see much point in assigning something to m
in order to return m
in the next line. Let's skip that step and just return.
As noted in comments, the square of the sum is always greater than the sum of the squares. So we can write the difference that way and leave out the abs
.
Empty lines can be useful for creating blocks of thought, but there's not that much going on in your function, so I'd say we don't really need those lines.
To be really pedantic, this is not your solution to problem #6. This is your function used to find the solution to problem #6, but the actual solution would be evaluating this function at 100.
I added a docstring to the function, so that you can call help(square_difference)
in other code.
I've removed some unnecessary parentheses.
This gives us:
def square_difference(n):
''' Return the difference between the square of the sum of the first n
natural numbers and the sum of the squares of the first n natural
numbers.
'''
sum_of_squares = n * (n + 1) * (2 * n + 1) / 6
sum_of_terms = n * (n + 1) / 2
return sum_of_terms**2 - sum_of_squares
print(square_difference(100))
If your function was really causing a bottleneck (it isn't), you could get a bit more performance out of this by using some algebra to find that the result is n*(n+1)*(3*n+2)*(n-1)/12
. But if you did that, you'd need a good comment explaining what is happening. As things are, we don't really need any comments.
m = k - l
); for example see this MSE question \$\endgroup\$