Issue with Sum of Odd Numbers Code
<p>I know that there are other post on this and I have referred to them but I can't seem to figure this one out.</p>

<p>This code gives me the value 2500, just 2500.</p>

<pre><code>sum = 0;
for i in range (1,100):
    if i % 2 == 1:
        sum = sum + i;
print (sum)
</code></pre>

<p>However I want the range to vary. So I came up with this</p>

<pre><code>def odd_sum_n(n):
    sum = 0;
    for i in range(1,2*n):
        if i % 2 != 0:
            sum = sum + i;
    print (sum)

print(odd_sum_n(5))
</code></pre>

<p>But this code gives me the solution</p>

<pre><code>25
None
</code></pre>

<p>I kept trying to adjusting this code but I don't see why the "None" appears. I'm new to python so any help would be appreciated!</p>

<p>Python considers that the return code is <code>None</code> for functions not returning anything</p>

<p>You actually have to RETURN sum not print it in your function </p>

<pre><code>def odd_sum_n(n):
    sum = 0;
    for i in range(1,2*n):
        if i % 2 != 0:
            sum += i;
    return (sum)

print(odd_sum_n(5))
</code></pre>

<p>BTW I would suggest to avoid using <code>sum</code> as it is a predefined function...</p>

<p>Note: another solution, shorter where we use prefedined <code>sum</code></p>

<pre><code>def odd_sum_n(n):
    return sum(range(1,2*n,2))

print(odd_sum_n(5))
</code></pre>

<p>for laughs: hjpotter92 comment is even better for this particular problem</p>

<pre><code>def odd_sum_n(n):
    return n*n
</code></pre>

<p>another classic serie: sum of all integers from 1 to n => <code>sum(range(n))</code> but also <code>n*(n+1)//2</code></p>

python