Python Help

[SSA]HellSpawn

Veteran XV
This is probally something real simple but I just started learning python and can't get it to work. So anyway While doing a loop i want it to print out every answer in a sequence, but all I can get is the one answer 3 times.

Any help would be appreciated. Thanks.

Code:
n = input("Please enter the number of terms you wish to sum:, ")
    for i in range(n):
     sum=4.0/((2*n)-1)
       
     print sum
 
No problem. Just invert your syntax so that your loop and the input string does the math backwards. The way you have it, you'll wind up with this:

e%20ball%20python%20male%20100%2011-02_jpg.jpg
 
Code:
n = input("Please enter the number of terms you wish to sum:, ")
for i in range(n):
    sum=4.0/((2*[b][i]i[/i][/b])-1)
       
    print sum
and if you want it to start at 1 instead of 0 change range(n) to range(1,n)
 
Last edited:
just add an if inside that loop that checks if i is odd (or even depends whether you want to start neg and if u start with 0 or 1)

I dont know if there is are odd/even functions but you can do
i%2==0 for even
i%2==1 for odd

print 0-sum if you need to else just print sum

edit: if you start your loop with i=0 it *may* freak out due to div by 0.
 
this is kindof a hack and programmtically not the best way to do it but i dont really care:

Code:
n = input("Please enter the number of terms you wish to sum:, ")
neg = 0
for i in range(n):
    sum=4.0/((2*i)-1)
    if neg==1:
        print 0-sum
        neg=0
    else:
        print sum
        neg=1

im reallly tired so test it but i think that should work
its really shitty though
 
A much much easier way is to do it like you would do with any alternating sequence.

Multiply the sum value by (-1)n. This way when the exponent n is even it will be the sum times +1 and if its odd it will be the sum times -1:

Code:
n = input("Please enter the number of terms you wish to sum:, ")
for i in range(n):
    sum=(4.0/((2*i)-1))*(-1)**i
    print sum

Of course with the equation and code you're using, it will start at n=0, so the first term will always be 4/(0-1) = -4. If you start the sequence at 1 (using range(1,n)), the (-1)n will make the first term negative. If you want to change the order of positives and negatives simply change the (-1)n to a (-1)n-1 or (-1)n+1:

Code:
n = input("Please enter the number of terms you wish to sum:, ")
for i in range(1, n):
    sum=4.0/((2*i)-1)*(-1)**(i-1)
    print sum
 
Last edited:
Back
Top