Python sqrt(x) Function to Calculate Square Root

An infographic providing a clear visual explanation of the Python sqrt() function. Learn how to calculate square roots of positive, negative and complex numbers in Python and its programs.

What is the Python sqrt() function?

  • The sqrt(x) function is used to get the square root of the given number in Python.
  • The sqrt() function is part of the math module.
  • You have to import it before using it in the Python program.
  • The value of x must be greater than 0.

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:

import math

print ("The Square root of 9 = " ,math.sqrt(9))

print ("The Square root of 25 = " ,math.sqrt(25))

print ("The Square root of 81 = " ,math.sqrt(81))

print ("The Square root of 90 = " ,math.sqrt(90))

print ("The Square root of 100 = " ,math.sqrt(100))

Output:

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:

import math

print ("The Square root of -25 = " ,math.sqrt(-25))

Result:

sqrt

You can see that 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 the sqrt() function is used to get the square root of the given number.

import math

try:
    a_number = float(input("Enter a number? "))
except ValueError:

    print ("Must enter a Number!")

else:
    print ("The Square root of",a_number ,"=" ,math.sqrt(a_number))

Sample output:

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.
Author - Atiq Zia

Atiq is the writer at jquery-az.com, an online tutorial website started in 2014. With a passion for coding and solutions, I navigate through various languages and frameworks. Follow along as we unravel the mysteries of coding together!