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
The square root of 30 is 5.4772 Check: 5.4772 x 5.4772 = 30.0000
How it works
import mathloads the math module, andmath.sqrt()returns the square root as a decimal number.- Negative numbers are checked first, because no real number multiplied by itself is negative, and
math.sqrt()raises an error for them. - The square root of 30 has endless decimal places, so
:.4frounds it to 4 of them. - 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
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 -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.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises