Editor

Python Program to Find the Square Root of a Number

Beginner · Numbers

The square root of a number is the value that gives the number when it is multiplied by itself: the square root of 25 is 5, because 5 x 5 = 25. This program finds a square root with the math module and checks the answer.

Program

square_root.py
import math
num = 30 # or: num = float(input("Enter a number: "))
if num < 0:
print("A negative number has no real square root")
else:
root = math.sqrt(num)
print(f"The square root of {num} is {root:.4f}")
print(f"Check: {root:.4f} x {root:.4f} = {root * root:.4f}")
Output
The square root of 30 is 5.4772
Check: 5.4772 x 5.4772 = 30.0000

How it works

  1. import math loads the math module, and math.sqrt() returns the square root as a decimal number.
  2. Negative numbers are checked first, because no real number multiplied by itself is negative, and math.sqrt() raises an error for them.
  3. The square root of 30 has endless decimal places, so :.4f rounds it to 4 of them.
  4. Multiplying the root by itself gives back the original number, which is a quick way to check the answer.

Other ways to write it

Using the ** operator

Using the ** operator
for num in [16, 2, 30, 144]:
root = num ** 0.5
print(f"Square root of {num} = {round(root, 4)}")
Output
Square root of 16 = 4.0
Square root of 2 = 1.4142
Square root of 30 = 5.4772
Square root of 144 = 12.0

Raising a number to the power 0.5 is the same as taking its square root, so num ** 0.5 needs no import.

Square root of a negative number

Square root of a negative number
import cmath
num = -16
root = cmath.sqrt(num)
print(f"Square root of {num} = {root}")
Output
Square root of -16 = 4j

The cmath module works with complex numbers, so instead of an error it returns 4j, which means 4 times the imaginary unit i.

Try it yourself

Print the square roots of every number from 1 to 10, rounded to 3 decimal places.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises