Last Updated On By Khizer Ali
Table of Contents
import math
math.sqrt(x);
Here, x is any positive number whose square root we want to find out.
Let’s have a look at few examples.
import math
num1 = 9
num2 = 7
num3 = 3.14
num4 = 6.09
sqrt_num1 = math.sqrt(num1)
sqrt_num2 = math.sqrt(num2)
sqrt_num3 = math.sqrt(num3)
sqrt_num4 = math.sqrt(num4)
print("math.sqrt(9) = " , sqrt_num1)
print("math.sqrt(7) = " , sqrt_num2)
print("math.sqrt(3.14) = " , sqrt_num3)
print("math.sqrt(6.09) = " , sqrt_num4)
In the above example, we passed positive values in math.sqrt() function and found their square root. We can see all the values that function returned are in float data type.
Pro Tip: What if we want the square root of any number in integer form? We can use the round() function for that purpose.
import math
num1 = -9
sqrt_num1 = math.sqrt(num1)
print("math.sqrt(-9) = " , sqrt_num1)
In the above example, we saw that if we are passing negative value to the math.sqrt() function, it is throwing an error exception.
Now, what if we have a negative number and want to find out its square root without any exception?
We can use abs() function to serve the purpose. Have a look at the example below.
import math
num1 = -9
abs_num1 = abs(num1)
sqrt_num1 = math.sqrt(abs_num1)
print("math.sqrt(abs(-9)) = " , sqrt_num1)
Here, abs() function will convert that negative number (-9) into a positive number and then math.sqrt() will find its square root.
In this article, we discussed math.sqrt() function used to find the square root of any positive number. This function was returning the value in float form. We discussed how we could get it in integer form, and finally, we saw how we could find out the square root of a negative number without an error.