I saw a video that claimed the following mathematical summation…
Can be implemented in Python as…
n = 10
i = 0
for i in range(n):
if i != 4:
i += 1
- The loop variable,
i
is being modified, which can be a risky programming technique, depending on the language. In Python, it does nothing. This code could be changed to usei += 100
and it wouldn't make a difference. It's unclear what the author intended here. - Doesn't sum the values of
i
, it only loops over them. No summation is done. -
range()
doesn't include the ending limit (i.e., this example goes up to 9, whereas mathematically, setting$n$ to 10 would include that number)
My advanced math skills are a little rusty, so I needed to check whether the upper limit is included in the summation. While I was researching, I saw several examples that use the Python range()
function incorrectly.
n = 10
summation = 0
for i in range(n + 1):
if i != 4:
summation += i
List comprehensions are more efficient than for
loops.
n = 10
summation = sum(i for i in range(n + 1) if i != 4)
Or don't use loops at all for the highest efficiency.
n = 10
summation = sum(filter(lambda i: i != 4, range(n + 1)))
Post a comment below.