Ways to Calculate Square Root in Python

I’ve found that calculating a square root is one of those tasks you’ll run into constantly.

Whether I am building a financial model for a Wall Street firm or a simple geometry script, knowing the right way to find a square root is essential.

In this tutorial, I will show you exactly how to calculate the square root in Python using various methods I’ve used in my own projects.

Method 1: Use the math.sqrt() Function

The most common way I calculate a square root is by using the built-in math module.

It is simple, highly optimized, and is the industry standard for most basic math operations in Python.

Suppose you are an architect in Chicago working on the layout for a new rectangular park. You know the area is 10,000 square feet, and you need to find the side length of a perfect square.

Here is the code I would use:

import math

# Area of a park in Chicago in square feet
area_sq_feet = 10000

# Calculating the side length of the square park
side_length = math.sqrt(area_sq_feet)

print(f"The side length of the park is {side_length} feet.")

You can refer to the screenshot below to see the output.

square root python

I prefer this method because the code is very readable. Anyone looking at your script will immediately understand what math.sqrt does.

Method 2: Use the Exponent Operator (**)

Sometimes, I don’t want to import an entire library just to do one simple calculation.

In Python, you can use the double asterisk ** for exponentiation. Since taking a square root is the same as raising a number to the power of 0.5, this works perfectly.

Let’s say you are calculating the distance for a delivery drone traveling between two points in New York City.

# Distance between two logistics hubs in kilometers
distance_squared = 169

# Calculating square root using the exponent operator
actual_distance = distance_squared ** 0.5

print(f"The drone delivery distance is {actual_distance} km.")

You can refer to the screenshot below to see the output.

sqrt in python

This is a “Pythonic” way to handle the problem without external dependencies. I use this frequently in quick scripts or lambda functions.

Method 3: Use the pow() Function

Another built-in option I often reach for is the pow() function.

It works similarly to the exponent operator but is a built-in function that some developers find cleaner to read.

Imagine you are working for a US-based fintech company and need to calculate the standard deviation, which involves square roots.

# Variance of a stock price on the NASDAQ
variance = 225

# Finding the standard deviation (square root of variance)
std_deviation = pow(variance, 0.5)

print(f"The standard deviation of the stock is {std_deviation}.")

You can refer to the screenshot below to see the output.

python square root

I’ve found that using pow() is helpful when you want to keep your syntax consistent with other functional programming styles.

Method 4: Calculate Square Roots of Negative Numbers (cmath)

Early in my career, I was surprised when my code crashed while trying to get the square root of a negative number using math.sqrt().

If you are working with complex electrical engineering data or advanced physics models, you will eventually hit a negative value.

In these cases, I use the cmath module, which is specifically designed for complex numbers.

import cmath

# A negative value from an electrical circuit calculation
negative_val = -64

# Calculating square root for complex numbers
complex_root = cmath.sqrt(negative_val)

print(f"The complex square root is: {complex_root}")

You can refer to the screenshot below to see the output.

python sqrt

This method is a lifesaver when you can’t guarantee that your input will always be a positive real number.

Method 5: Use NumPy for Arrays and Lists

If you are a data scientist or working with large datasets, like analyzing housing prices across the United States, you shouldn’t use a loop.

Instead, I always use NumPy. It allows you to calculate the square root of an entire list (array) of numbers simultaneously.

import numpy as np

# A list of plot areas in a new Texas housing development
plot_areas = np.array([1600, 2500, 3600, 4900])

# Calculating square roots for the entire array at once
side_lengths = np.sqrt(plot_areas)

print("The side lengths for the Texas housing plots are:")
print(side_lengths)

In my experience, NumPy is significantly faster when dealing with thousands of data points compared to standard Python lists.

Handle Errors and Edge Cases

Whenever I write production-level code, I make sure to handle potential errors.

If a user inputs a string instead of a number, or if you accidentally pass a negative number to math.sqrt(), your program will stop.

Here is how I usually wrap my square root logic to make it “bulletproof”:

import math

def get_safe_sqrt(value):
    try:
        if value < 0:
            return "Error: Cannot calculate real square root of a negative number."
        return math.sqrt(value)
    except TypeError:
        return "Error: Please provide a valid numeric value."

# Example usage
print(get_safe_sqrt(144))
print(get_safe_sqrt(-9))
print(get_safe_sqrt("Seattle"))

Adding these simple checks has saved me from many late-night debugging sessions.

Comparison Table: Which Method Should You Use?

In my work, I choose the method based on the specific requirements of the project. Here is a quick breakdown of how I decide:

MethodBest ForRequirement
math.sqrt()General use and readabilityimport math
** 0.5Quick calculations/Small scriptsNo import needed
pow(x, 0.5)Functional programming styleNo import needed
cmath.sqrt()Complex numbers/Engineeringimport cmath
np.sqrt()Data Science/Large datasetsimport numpy

I hope this tutorial helped you understand the different ways to handle square roots in Python.

While there are many ways to do it, I usually stick to math.sqrt for its clarity and NumPy for any heavy lifting involving data.

You may also read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.