Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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)
            break
        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
test_sqrt(3)

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

print(y)
return y
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading