Square root in python function is the predefined function. To use the square root function in python we need to import the math library in the code. The sqrt() returns the square root of any number.
How to use square root in python?
Import the math library in the code. Either pass the number to the function directly or accept a number from the user and pass it to the function. This function will the square root of the passed number store it in a variable or directly print it. If the number passed to the function is less than zero then the interpreter will show the error at run time.
Syntax of square root function in python
Import math Variable = math.sqrt(positive number)
Table of Contents
A simple program to find the square root of a number.
In this example, we are passing a positive integer to the function square root in python 3.
import math x = math.sqrt(1323) #square root of 1323 y = math.sqrt(83.93) #square root of 83.93 z = math.sqrt(0.56743) #square root of 0.56743 print(x) print(y) print(z)
36.373066958946424 9.161331780914825 0.7532794966013611
Passing a negative integer to the square root function.
The interpreter will throw an exception at runtime
import math x = math.sqrt(-47) #square root of 1323 print(x)
x = math.sqrt(-47) #square root of 1323 ValueError: math domain error
Finding the square root of complex numbers
import cmath num = 18+5j x = cmath.sqrt(num) #square root of 18+5j print(x)
Without using the Square root function
We can find the square root of any integer without using the Square root function. Let’s have a look
# finding square root of number without using sqrt() num = 49 ** (1/2) print(num)
Find the hypotenuse of a right-angled triangle in python
import math a = int(input('Enter length of 1st side of right angled triangle : ')) b = int(input('Enter length of 1st side of right angled triangle : ')) c = math.sqrt((a*a)+(b*b)) print(c)
Enter length of 1st side of right angled triangle : 9 Enter length of 1st side of right angled triangle : 10 13.45362404707371
Either you can use the predefined function square root in python or you can use the exponentiation operator provided by python and simply multiply by ½ to the number.