w3resource logo

:

Python Exercises

Python Challenges: Compute and return the square root of a given integer

Python Challenges - 1: Exercise-11 with Solution

Write a Python program to compute and return the square root of a given 'integer'.

Note: The returned value will be an ‘integer’.

Python: Square root

Sample Solution:-

Python Code:

def my_sqrt(x):
   if x<2: return x
   left=1
   right=int(x/2)+1
   while left<=right:
            mid=int((left+right)/2)
            if mid*mid==x:
                return mid
            if mid*mid>x:
                right=mid-1
            else:
                left=mid+1
   return right

print(my_sqrt(16))

Sample Output:

4 

Flowchart:

Python Flowchart: Compute and return the square root of  an  given 'integer'

Python Code Editor:

Improve this sample solution and post your code through Disqus