The sqrt(x) function in Python

The sqrt(x) function is used to get the square root of the given number in Python. The sqrt() function is the part of math module so you need to import it before using in Python program.

The value of x must be greater than 0.

Square root example

Syntax of using the sqrt function

This is how you may use the square root function:

math.sqrt( x )

For example:

math.sqrt(25)

The sqrt method returns the square root of the given number that must be greater than 0.

Note that, by default, the math functions return the float values.

An example of getting the square root

In this example, the Python program is written for getting the square root of 9, 25, 81, 90 and 100 numbers. See the code and output:

See online demo and code

Python square root

An example of using the negative number

What if we provide the number less than 0 i.e. a negative number? See this example, where provided the -25 value to the sqrt() function:

See online demo and code

 

Python sqrt

You can see, an error is generated that says ValueError: math domain error.

Calculating the user given value’s square root example

In this example, the input function is used to get the user input for entering a number. The entered number is converted to float and sqrt() function is used to get the square root of the given number.

See online demo and code

 

Python sqrt user number

Note: If you enter a string, the error handler will stop the execution and a message will display to enter a number.