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'.

Input : 16
Output : 4

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))

Output :

4

Flowchart:

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

Python Code Editor:

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))

Improve this sample solution and post your code through Disqus



Join our Question Answer community to learn and share your programming knowledge.

Solve these problems:

Python: How to check whether a file exists using Python?

C#: Loops in c#

PHP: For each

SQL: JOIN using more than 5 tables

JavaScript: Blank Slide in Javascript Slideshow