Calculating Pi (π) with Python

This is important questions asked in many pair programming interviews.

In python there is simple way to calculate the value using Math.pi library However this is not expected in the interview.

Formula : π (Pi) = 4 * (1 - 1/3 + 1/5 - 1/7 + 1/9 - ...)

Usually its asked in interview to write program in for equations 1-1/3+1/5-1/7+1/9---

and for pi (π) 4(1-1/3+1/5-1/7+1/9------ so on)

Program :


def CalculatePivalue(n):
    sum=0
    flag=0
    for i in range(1,n):
        if i%2 !=0:
            if flag==0:
                sum+=(1/i)
                flag=1
            else:
                sum -= (1/i)
                flag = 0
    return sum*4

print(CalculatePivalue(10000))

Output : 3.141392653591791