0

This is a simple program consisting of two functions. The newton function should return an estimate of the square root of a given number but instead returns none and I don't understand why. Can someone give me some pointers.

Thank you

import math
# Initialize the tolerance
TOLERANCE = 0.000001
estimate = 1.0


def newton(x, estimate):
    """Returns the square root of x."""
    # Perform the successive approximations
    estimate = (estimate + x / estimate) / 2
    difference = abs(x - estimate ** 2)
    if difference <= TOLERANCE:
        return estimate
    #In this else statement I want to pass the values x 
    #and estimate as they currently exist in the newton 
    #function back into another run of newton. I want this to be a recursive function. 
    else:
        newton(x, estimate)


def main():
    """Allows the user to obtain square roots."""
    while True:
        # Receive the input number from the user
        x = input("Enter a positive number or enter/return to quit: ")
        if x == "":
            break
        x = float(x)
        # Output the result
        print("The program's estimate is", newton(x, estimate))
        print("Python's estimate is     ", math.sqrt(x))


if __name__ == "__main__":
    main()
David G
  • 11
  • 2
  • 1
    Last line should be `return newton(x, estimate)`. A function that ends without a `return` implicitly does `return None`. – BoarGules Jul 27 '21 at 04:15

1 Answers1

0

Simply, at the end of the function:

else:
    newton(x, estimate)

You should be returning the value from the recursive call, ie:

else:
    return newton(x, estimate)
Ken Y-N
  • 14,644
  • 21
  • 71
  • 114