'Python - Different result from while loop than when in a user defined function

I am trying to create a code that returns a approximation of pi given n iterations that the user will give. The higher n the more accurate.

I created a while loop to do this, and it works fine:

import math

x = 1
k = 0
n = int(input("Enter n:"))
while x <= n:
    k=k+(1/x**2) # summation of 1/k**2 for every n times
    y=k*6 # multiply k by 6 like in formula
    fin = math.sqrt(y) # find sqrt of y like in the formula
    x += 1

print(fin)

But now I'm trying to make this into a function. This is what I've come up with:

import math

def pi(n):
    x = 1
    k = 0
    #n = int(input("Enter n:"))
    while x <= n:
        k=k+(1/x**2) # summation of 1/k**2 for every n times
        y=k*6 # multiply k by 6 like in formula
        fin = math.sqrt(y) # find sqrt of y like in the formula
        x += 1
        return fin

g=pi(int(input("Enter n:")))
print(g)

For some reason I get different answers... why is it when I use the function that the answer becomes inaccurate?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source