How to use square root function: sqrt() in Python

In this tutorial, we will learn about the square root function sqrt() in Python.

Python contains many useful functions. In that, it also includes the square root function sqrt().

Python square root function: sqrt()

The Python sqrt() function is used to get the square root of a given number.

It is an inbuilt function in Python programming language.

As the square root is a mathematical operation, the sqrt() function is available in the math module. So, first while writing a program import the math package.

import math

syntax to use sqrt() function is:

math.sqrt(x)

Here, x is a number for which square root has to be calculated. It may be int or float types.

The return type of sqrt() function is float.

The parameter value of the function sqrt() should not be negative.

Let’s see some examples:

First, we write the program for calculating the square root of a positive integer,

import math
print("square root of 25 is",math.sqrt(25))

output:

square root of 25 is 5.0

we will see another example which gives the output that is not a perfect square,

import math
print("square root of 10 is",math.sqrt(10))

output:

square root of 10 is 3.1622776601683795

Let’s see the output by giving the parameter value as 0,

import math
print("square root of 0 is",math.sqrt(0))

output:

square root of 0 is 0.0

As the parameter of the sqrt() function should be greater than or equal to 0.

Let’s see the output if we give the parameter value less than 0,

import math
print("square root of -5 is",math.sqrt(-5))

output:

Traceback (most recent call last):
File "sqrt.py", line 2, in <module>
print("square root of -5 is",math.sqrt(-5))
ValueError: math domain error

So, when x<0 it does not execute instead generates a ValueError.

Now, we will see the output by giving the floating-point number,

import math
print("square root of 5.5 is",math.sqrt(5.5))

output:

square root of 5.5 is 2.345207879911715

Let’s see the square root of value pi,

import math
print("square root of pi is",math.sqrt(math.pi))

output:

square root of pi is 1.7724538509055159

Also read:

Leave a Reply

Your email address will not be published. Required fields are marked *