Returning a table containing square root of number passed to the function in python


Below in the first function I‌ return the square root of any value passed as the argument and it is working fine when I call it and in the second function at the part of mysqrt variable it doesn’t return the mysqrt(num) returns a value of none, so it gives an error at the diff variable while the value of mysqrt(a) is none.

import math
epsilon = 0.0000001
def my_sqrt(a):
    x = a/2
    while True:
        y = (x + a/x) / 2
        if y == x:
            return print(y)
        x = y

def test_sqrt(a):
    num = 1
    while a >= num:
        a_value = f"a = {num} |"
        mysqrt = f"my_sqrt(a) = {my_sqrt(num)} |"
        mathsqrt = f"math.sqrt(a) = {math.sqrt(num)} |"
        diff = f"diff = {my_sqrt(num) - math.sqrt(num)}"
        print(a_value, mysqrt, mathsqrt, diff)
        num = num + 1

I tried to hard code it to the print function but it doesn’t work, and I am expected that it returns a value instead of none.

>Solution :

I think the problem is that you are returning the result of the print statement. you should refactor it like:

return y

Leave a ReplyCancel reply