Q:

python 2 division

#this works in python 3
def pi_sum(n):
    total, k = 0,1
    while k <= n:
        total, k = total +8 /(k *(k+2)), k + 4
    return total

#this is how i tried to fix it for python 2
def pi_sum2(n):
    total, k = 0,1
    while k <= n:
        total, k = float(total +8) /(k *(k+2)), k + 4
    return total

In python 2: for pi_sum2(1e6) I get 8.000032000112001e-12.   What's wrong here? 
EDIT above my first mistake was applying float to both total and 8..
i should have done:
#this is how i tried to fix it for python 2
def pi_sum2(n):
    total, k = 0,1
    while k <= n:
        total, k = total + float(8) /(k *(k+2)), k + 4
    return total

A:

You need to define your variables explicitly as floats to avoid some type coersion:
def pi_sum(n):
    total, k = 0.0, 1.0
    while k <= n:
        total, k = total + 8.0 /(k *(k+2)), k + 4
    return total

should do the trick

