There are three common ways to get a square root in Python. All three are short, but they give different types of result.
The program
import math n = 144 print(n ** 0.5) print(math.sqrt(n)) print(math.isqrt(n)) print(math.isqrt(150)) print(2 ** 0.5)
12.0 12.0 12 12 1.4142135623730951
How it works
n ** 0.5raises n to the power one half, which is the square root. It needs no import, and the result is a float.math.sqrt(n)gives the same float. Many people find it easier to read.math.isqrt(n)gives the integer square root: the largest whole number whose square is not more than n. For 150 it is 12, because 12² = 144 and 13² = 169. It is exact even for very large whole numbers.- The square root of 2 has no end to its decimals, so the float result is rounded to about 16 significant digits.
Negative numbers
A negative number has no real square root. math.sqrt(-4) raises ValueError: math domain error. The cmath module works with complex numbers and does give an answer:
import cmath print(cmath.sqrt(-4))
2j
j is how Python writes the imaginary unit i (the square root of -1). If you do not need complex numbers, check if n < 0: before calling math.sqrt().
By hand: Newton's method
Without any library, you can start with a guess and improve it. Each new guess is the average of the guess and n / guess:
n = 2 guess = n / 2 for step in range(1, 6): guess = (guess + n / guess) / 2 print(step, guess)
1 1.5 2 1.4166666666666665 3 1.4142156862745097 4 1.4142135623746899 5 1.414213562373095
If the guess is too big, n / guess is too small, so their average is closer to the real root. The number of correct digits roughly doubles at each step. After 5 steps, every digit matches 2 ** 0.5 except the last one. That small difference comes from rounding in float arithmetic.