Help me with this code

Piet van Oostrum piet at vanoostrum.org
Thu Nov 7 14:08:06 CET 2013


chovdary at gmail.com writes:


> Hi friends
>
> help me with the following code. Im able to execute the code but getting wrong output
>
> def sequence_b(N):
>     N = 10
>     result = 0
>     for k in xrange (1,N):
>         result  +=  ((-1) ** (k+1))/2*k-1
>         print result
> print sequence_b(10)
>
> This is the output which im getting
> -1
> -4
> -5
> -10
> -11
> -18
> -19
> -28
> -29
>
>
> But i want output as
> 1
> -1/3
> 1/5
> -1/7
> 1/9
> -1/11
> 1/13
> -1/15
> 1/17
> -1/19

You probably want this:

N = 10
result = 0
for k in range (1,N):
    step = ((-1)**(k+1))/(2*k-1)
    result += step
    print(step)

Note: 
1. You don't use the parameter N, you immediately change it to 10. Leave the line N = 10 out.
2. Your function doesn't return its result, so it returns None. So the print sequence_b(10) dosn't make sense.
If the print is only for debugging the use the following:

def sequence_b(N):
    result = 0
    for k in range (1,N):
        step = ((-1)**(k+1))/(2*k-1)
        print(step) ## debug output
        result += step
    return result

print(sequence_b(10)) # print the result of the function call

[I use print() because I use Python 3]
-- 
Piet van Oostrum <piet at vanoostrum.org>
WWW: http://pietvanoostrum.com/
PGP key: [8DAE142BE17999C4]



More information about the Python-list mailing list