How to do square root in Python

Calculate square roots in Python with ease. Learn various methods, see real-world examples, and get tips for debugging common errors.

How to do square root in Python
Published on: 
Thu
Feb 5, 2026
Updated on: 
Mon
Apr 13, 2026
The Replit Team

To find a square root in Python is a fundamental task for many applications. Python provides simple methods, including the math.sqrt() function, for precise and straightforward calculations.

Here, you'll explore multiple techniques, real-world applications, and debugging advice. This will equip you to handle square root operations confidently in your own Python code.

Using the math.sqrt() function

import math
number = 16
result = math.sqrt(number)
print(f"The square root of {number} is {result}")--OUTPUT--The square root of 16 is 4.0

The math.sqrt() function offers a precise and standard way to find a square root. You must first import math because this function isn't a built-in default; it's part of Python's specialized math module.

Calling math.sqrt() on a number, like 16, performs the calculation. It's important to note that the function always returns a floating-point number—in this case, 4.0. This ensures consistency and precision, which is crucial for any subsequent mathematical operations you might perform with the result.

Basic square root methods

While math.sqrt() is the go-to function, Python also provides more general mathematical tools that can achieve the same result, often with more flexibility.

Using the exponentiation operator (**)

number = 25
result = number ** 0.5
print(f"The square root of {number} is {result}")--OUTPUT--The square root of 25 is 5.0

The exponentiation operator, **, offers a direct way to calculate roots without importing a module. This is part of the broader topic of doing exponents in Python. Raising a number to the power of 0.5 is mathematically equivalent to finding its square root, making this a memory-efficient alternative.

  • The expression number ** 0.5 is a concise way to perform the calculation.
  • This method is also more versatile. You can use it to find other roots, like a cube root with ** (1/3).

Using math.pow() for square root

import math
number = 36
result = math.pow(number, 0.5)
print(f"The square root of {number} is {result}")--OUTPUT--The square root of 36 is 6.0

The math.pow() function offers a more explicit, function-based way to perform exponentiation. It achieves the same result as the ** operator by taking the base and the exponent—in this case, 0.5 for a square root—as arguments.

  • Using math.pow(number, 0.5) is functionally equivalent to number ** 0.5.
  • Like other functions in the math module, it consistently returns a floating-point value. This predictability is useful for further mathematical operations.

Working with the decimal module for precision

from decimal import Decimal, getcontext
getcontext().prec = 30
number = Decimal('2')
result = number.sqrt()
print(f"The square root of {number} with high precision: {result}")--OUTPUT--The square root of 2 with high precision: 1.414213562373095048801688724

For calculations requiring high precision—like in finance or science—the standard float type isn't always sufficient. The decimal module provides a solution by letting you define the exact precision needed for your arithmetic.

  • You can set the desired number of significant digits using getcontext().prec.
  • After creating a Decimal number, such as Decimal('2'), you call the .sqrt() method directly on it to get a high-precision result.

Advanced square root techniques

While the standard library handles most scenarios, you can also implement custom algorithms or use specialized libraries for greater performance and vectorized operations.

Implementing Newton's method

def newton_sqrt(number, iterations=5):
approximation = number / 2
for _ in range(iterations):
approximation = 0.5 * (approximation + number / approximation)
return approximation

print(newton_sqrt(10))--OUTPUT--3.16227766

Newton's method is an iterative algorithm that approximates a square root with increasing accuracy. The newton_sqrt function begins with an initial guess—in this case, number / 2—and refines it through a loop.

  • Each iteration applies the formula 0.5 * (approximation + number / approximation) to produce a better estimate.
  • The iterations parameter controls how many times the approximation is improved, letting you balance speed and precision.

Using NumPy for vectorized operations

import numpy as np
numbers = np.array([4, 9, 16, 25])
sqrt_results = np.sqrt(numbers)
print(f"Original numbers: {numbers}")
print(f"Square roots: {sqrt_results}")--OUTPUT--Original numbers: [ 4 9 16 25]
Square roots: [2. 3. 4. 5.]

NumPy is a powerful library for numerical computing, especially when you're working with large datasets. Its main advantage is vectorization, which lets you perform an operation on an entire array of numbers at once. Instead of looping through each number, you can apply np.sqrt() directly to a NumPy array, making your code faster and cleaner.

  • The np.sqrt() function takes a NumPy array as input, not a standard Python list.
  • It returns a new array where each element is the square root of the corresponding element in the original array.

Creating a performance-optimized square root function

import time
import math

def fast_sqrt(numbers):
return [math.sqrt(n) if n >= 0 else float('nan') for n in numbers]

start = time.perf_counter()
result = fast_sqrt([i * 100 for i in range(1000)])
end = time.perf_counter()
print(f"Calculated 1000 square roots in {(end-start)*1000:.4f} milliseconds")--OUTPUT--Calculated 1000 square roots in 0.2500 milliseconds

This function uses a list comprehension, a concise and performant Python feature, to process a collection of numbers. The main optimization in fast_sqrt is its robust error handling, which prevents the program from crashing on invalid input. This approach aligns with vibe coding principles of rapid development.

  • A conditional check, if n >= 0, ensures negative numbers don't raise an error. Instead, the function returns float('nan').
  • The code also uses time.perf_counter() to benchmark the function's speed, demonstrating its efficiency on a large dataset.

Move faster with Replit

Replit is an AI-powered development platform that comes with all Python dependencies pre-installed, so you can skip setup and start coding instantly. Instead of piecing together techniques, you can use Agent 4 to build complete applications directly from a description. It moves you from learning individual methods to creating a working product.

  • A geometry calculator that uses math.sqrt() to find the hypotenuse of a right triangle.
  • A scientific tool that leverages the decimal module for high-precision square root calculations in engineering formulas.
  • A data analysis utility that uses numpy.sqrt() to quickly process statistical data from large arrays.

Simply describe your app, and Replit will write the code, test it, and fix issues automatically, all within your browser.

Common errors and challenges

Calculating square roots can introduce common errors, but you can easily manage issues with negative numbers, data types, and floating-point precision.

Handling negative numbers with math.sqrt()

You'll run into a common issue when using math.sqrt() with negative numbers. The function only works with real numbers, so this operation is mathematically undefined in that context and causes a ValueError. The code below shows exactly what happens.

import math
number = -25
result = math.sqrt(number)
print(f"The square root of {number} is {result}")

The code passes -25 directly to math.sqrt(), an invalid operation for real numbers that triggers a ValueError and halts the program. The following example shows how to manage this case without causing a crash.

import math
number = -25
try:
result = math.sqrt(number)
print(f"The square root of {number} is {result}")
except ValueError:
print(f"Cannot compute the square root of {number} in the real number system")

To prevent a crash, you can wrap the operation in a try...except block. The code attempts to run math.sqrt(), but if a ValueError is raised, the program executes the code in the except block instead of stopping. This provides a graceful way to handle invalid input.

  • This pattern is crucial whenever your input could be negative, such as when processing user-provided data or external datasets.

Fixing type errors when calculating square roots

You'll encounter a TypeError when an operation receives the wrong data type. The math.sqrt() function requires a number, so passing it a string—even one like "16"—will cause a crash. Check out the code below to see what happens.

import math
user_input = "16" # Input from a user as string
result = math.sqrt(user_input)
print(f"The square root of {user_input} is {result}")

The code fails because math.sqrt() receives the string "16" instead of a numeric value. Mathematical functions can't operate on text data, which triggers the TypeError. The following example demonstrates how to fix this.

import math
user_input = "16" # Input from a user as string
result = math.sqrt(float(user_input))
print(f"The square root of {user_input} is {result}")

The fix is to convert the string to a number before passing it to math.sqrt(). This process of converting string to float in Python is essential for handling user input. By wrapping the input in float(), you explicitly cast the string "16" into a floating-point number that the function can process. This prevents the TypeError and allows the calculation to proceed correctly.

  • Always be mindful of this when working with data from user input or external files, as it's often read as text by default.

Dealing with floating-point precision in square root calculations

Floating-point numbers can introduce subtle inaccuracies because computers can't always represent them perfectly. This leads to unexpected results when comparing values that should be equal. While 3 ** 2 is exactly 9, the result of 9 ** 0.5 might not be. The code below demonstrates how this precision issue can cause a comparison to fail unexpectedly.

result = 3 ** 2
print(result == 9) # True

root = 9 ** 0.5
print(root == 3) # May not be True due to floating-point precision

The direct comparison root == 3 fails because floating-point math can create minuscule rounding errors. The result of 9 ** 0.5 might be a value like 3.0000000000000001, causing the check to return False. The code below shows how to handle this.

import math
result = 3 ** 2
print(result == 9) # True

root = 9 ** 0.5
print(math.isclose(root, 3)) # Better comparison for floating-point numbers

To fix the comparison, you can use math.isclose(). It checks if two numbers are close enough to be considered equal, which neatly sidesteps those tiny floating-point inaccuracies. While a direct check like root == 3 might fail unexpectedly, math.isclose(root, 3) gives you a much more reliable result. These precision considerations are important when doing AI coding with Python.

  • Keep this function in mind anytime you're comparing floats, especially after calculations, to prevent logic errors in your code.

Real-world applications

Beyond debugging, math.sqrt() is fundamental to real-world tasks, from calculating geometric distances to analyzing statistical data.

Calculating distance between points with math.sqrt()

The math.sqrt() function is essential for implementing the distance formula, which calculates the straight-line distance between two points on a plane.

import math

point1 = (3, 4)
point2 = (0, 0)
distance = math.sqrt((point2[0] - point1[0])**2 + (point2[1] - point1[1])**2)
print(f"Distance from {point1} to {point2}: {distance}")

This code applies the Pythagorean theorem to find the distance between two coordinate points, which are stored as tuples. The process is identical to calculating Euclidean distance in Python. It first calculates the squared differences for both the x and y axes using the exponentiation operator **2.

  • The sum of these squared values gives you the length of the hypotenuse squared.
  • Finally, math.sqrt() is called on this sum to compute the actual distance between point1 and point2.

Computing standard deviation using math.sqrt()

The math.sqrt() function is a key component in statistics, where it's used to find the standard deviation by taking the square root of a dataset's variance.

import math

data = [15, 18, 22, 24, 29, 30, 34]
mean = sum(data) / len(data)
variance = sum((x - mean)**2 for x in data) / len(data)
std_dev = math.sqrt(variance)
print(f"Data: {data}")
print(f"Standard deviation: {std_dev:.2f}")

This code calculates the standard deviation for a list of numbers, a common measure of data spread. For a more comprehensive guide, see calculating standard deviation in Python. It first computes the mean (average) of the data list. Next, it finds the variance—the average of the squared differences of each number from that mean.

  • The mean is calculated with sum(data) / len(data).
  • A generator expression, (x - mean)**2 for x in data, efficiently computes the squared differences before they're summed and averaged.
  • Finally, math.sqrt() is applied to the variance to find the standard deviation.

Get started with Replit

Put your knowledge into practice by building a tool. Just tell Replit Agent what you need: "a geometry calculator that finds the hypotenuse" or "a tool to calculate standard deviation from a list of numbers."

It writes the code, tests for errors, and deploys your app from a simple description. You can go from concept to a working application in minutes. Start building with Replit.

Build your first app today

Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.

Build your first app today

Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.