Home » Python Tutorial » Python Square Root with examples

Python Square Root with examples

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

Syntax:

Import math
Variable = math.sqrt(positive number)

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. 

Example:

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)

Output

36.373066958946424
9.161331780914825
0.7532794966013611

Passing a negative integer to the square root function.

The interpreter will throw an exception at runtime

Example:

import math
x = math.sqrt(-47) #square root of 1323
print(x)

Error

x = math.sqrt(-47) #square root of 1323
ValueError: math domain error

Finding the square root of complex numbers

Example:

import cmath

num = 18+5j
x = cmath.sqrt(num) #square root of 18+5j

print(x)

Output

4.282612619200423+0.5837558103648324j

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

Example:

# finding square root of number without using sqrt()
num = 49 ** (1/2)
print(num)

Output

7.0

Find the hypotenuse of a right-angled triangle in python

Example:

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)

Output

Enter length of 1st side of right angled triangle : 9
Enter length of 1st side of right angled triangle : 10
13.45362404707371
How to do a square root in python?

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.

Did you know?
1. Python Bisect Algorithm
2. Palindrome in Python
3. Armstrong Number In Python
4. Absolute Value in Python
5. Leap Year Program in Python
6. Factorial Program in Python
7. Python Split with Examples
8. Python Substring
9. Features of Python
10. Python Square Root

Pin It on Pinterest