How to do square root in Python
Learn how to calculate the square root in Python. Discover multiple methods, tips, real-world applications, and how to debug common errors.

Python provides several simple methods to find the square root of a number. These built-in functions and modules make the calculation straightforward for any developer.
You'll learn multiple techniques, from the ** operator to the math.sqrt() function. You'll also get practical tips, see real-world applications, and receive advice for debugging common errors.
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 is a precise tool for finding a square root. It lives inside Python's standard math module, so you must import the module before using it. This approach is often favored for a few key reasons:
- Clarity: Using a named function like
math.sqrt()makes your code's intent immediately obvious to anyone reading it. - Consistency: It always returns a floating-point number, as shown by the
4.0output. This ensures your results have a predictable data type for further calculations.
This makes it a reliable and readable choice for mathematical code.
Basic square root methods
While math.sqrt() is a direct approach, Python also provides more general mathematical tools for calculating square roots, offering flexibility for different programming needs.
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, **, is Python's built-in tool for raising a number to a power. Finding a square root is the same as raising a number to the power of 0.5, so you can use number ** 0.5 to achieve this.
- Flexibility: This approach isn't limited to square roots. You can find any root simply by changing the exponent, such as using
** (1/3)for a cube root. - Type Consistency: It returns a floating-point number, just like
math.sqrt(), which helps keep your data types predictable for later math operations.
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 is another tool from the math module that works much like the exponentiation operator. It takes two arguments—the number and the power you want to raise it to. By passing 0.5 as the second argument, you can calculate the square root.
- Functional Similarity: It's essentially a function-based version of using the
**operator, offering a different stylistic choice for your code. - Float Output: Like the other methods,
math.pow()consistently returns a floating-point number, which helps maintain type consistency in mathematical calculations.
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
When standard floating-point math isn't precise enough, the decimal module is your go-to solution. It's designed for calculations where you need exact decimal representation—like in finance or science—avoiding the small inaccuracies of regular floats. You get full control over the level of precision.
- You first set the desired number of significant digits using
getcontext().prec. - Then, you create a
Decimalobject from your number and call its own.sqrt()method to get a high-precision result.
Advanced square root techniques
For situations demanding more control or performance, you can move beyond built-in functions and implement custom algorithms or leverage powerful scientific computing libraries.
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 offers a way to calculate a square root by implementing a classic numerical algorithm yourself. It works by starting with an initial guess—in this case, number / 2—and then repeatedly refining that guess to get closer to the actual root.
- The core of the function is a loop that improves the
approximationwith each pass, making it more accurate. - You can control the precision by adjusting the number of
iterations. More loops yield a more precise answer, giving you direct influence over the trade-off between speed and accuracy.
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.]
For large datasets, the NumPy library is a game-changer. Its np.sqrt() function performs a vectorized operation, meaning it calculates the square root of every number in an array all at once. This is far more efficient than looping through each item individually.
- Performance: Vectorized operations are highly optimized and run much faster than equivalent Python loops, especially with large amounts of data.
- Readability: The code is clean and concise. You apply the function directly to the array, making your intent clear without extra boilerplate.
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
You can build a fast and robust function using a list comprehension. The fast_sqrt function processes an entire list of numbers in a single, readable line, applying math.sqrt() to each valid item. This approach is often more efficient than a standard for loop for simple transformations.
- Built-in Error Handling: The function checks each number with
if n >= 0. If it encounters a negative number, it returnsfloat('nan')instead of raising an error, making your code more resilient. - Pythonic Efficiency: List comprehensions are a core feature of Python, celebrated for their clarity and performance in creating new lists.
Move faster with Replit
Replit is an AI-powered development platform that transforms natural language into working applications. Describe what you want to build, and Replit Agent creates it—complete with databases, APIs, and deployment.
For the square root techniques we've explored, Replit Agent can turn them into production tools. Here are a few examples:
- Build a geometry calculator that uses the Pythagorean theorem to find the length of a triangle's hypotenuse.
- Create a high-precision scientific tool for physics simulations that requires the accuracy of the
decimalmodule. - Deploy a data analysis dashboard that processes large arrays of numbers efficiently with vectorized functions like
numpy.sqrt().
Describe your app idea, and Replit Agent writes the code, tests it, and fixes issues automatically, all in your browser.
Common errors and challenges
Calculating square roots in Python is straightforward, but a few common issues can catch you off guard if you're not prepared.
Handling negative numbers with math.sqrt()
One of the most frequent errors is a ValueError. This happens when you try to find the square root of a negative number using math.sqrt(), since the function is only defined for non-negative values.
- To prevent this, you can add a simple check like
if number >= 0:before calling the function. - Alternatively, you can use a
try-exceptblock to catch theValueErrorand handle it gracefully, perhaps by returning a message or a specific value like'nan'.
Fixing type errors when calculating square roots
Another common problem is the TypeError. This error appears when you pass a non-numeric value, such as a string, to a mathematical function like math.sqrt() or math.pow().
This often occurs with user input, which is typically read as a string. Always make sure to convert your input to a number using int() or float() before performing any calculations to avoid this error.
Dealing with floating-point precision in square root calculations
Finally, it's important to understand the limitations of floating-point arithmetic. Because of how computers store these numbers, calculations can sometimes have tiny precision errors. For example, squaring the result of math.sqrt(2) might give you 2.0000000000000004 instead of exactly 2.0.
For most everyday applications, this level of imprecision is perfectly acceptable. However, if you're working in a field like finance or scientific computing where exactness is critical, you should use the decimal module for high-precision results.
Handling negative numbers with math.sqrt()
The math.sqrt() function is designed for real numbers, so it can't process negative inputs. Attempting to find the square root of a negative number will immediately raise a ValueError, stopping your program. See what happens when you try it below.
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(), which can't handle negative inputs and triggers a ValueError. To prevent your program from crashing, you need to handle this possibility. See how to manage this error in the example below.
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")
By wrapping the calculation in a try-except block, you can gracefully manage this error. Python first attempts the code inside the try statement. If a ValueError is raised, the program doesn't crash. It instead executes the code within the except block. This approach is essential when working with user input or external data, where you can't always guarantee the numbers will be non-negative, keeping your application from stopping unexpectedly.
Fixing type errors when calculating square roots
A TypeError is another common hurdle, appearing when you pass a non-numeric value like a string to a function such as math.sqrt(). This frequently occurs with user input, which Python reads as text. See what happens in the code below.
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 math.sqrt() function requires a number, but it receives the string "16". This data type mismatch triggers a TypeError. The following example shows how to correctly handle string input before performing the calculation.
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 explicitly convert the string to a number before passing it to math.sqrt(). By wrapping user_input in float(), you transform the text "16" into the numeric value 16.0, which satisfies the function's requirement. This is a crucial step whenever you're working with data from user input, since it's almost always received as a string and needs conversion for mathematical operations.
Dealing with floating-point precision in square root calculations
Floating-point arithmetic isn't always exact. Because of how computers store decimals, calculations can introduce tiny rounding errors. This means an operation you expect to be perfect, like 9 ** 0.5, might not yield exactly 3. The code below demonstrates this discrepancy.
result = 3 ** 2
print(result == 9) # True
root = 9 ** 0.5
print(root == 3) # May not be True due to floating-point precision
The == operator demands exact equality. While 3 ** 2 is precisely 9, the result of 9 ** 0.5 might be a float that's infinitesimally different from 3, causing the comparison to fail. The code below shows a reliable way to compare these values.
import math
result = 3 ** 2
print(result == 9) # True
root = 9 ** 0.5
print(math.isclose(root, 3)) # Better comparison for floating-point numbers
Instead of using the == operator, which demands perfect equality, the math.isclose() function is a much safer bet for comparing floats. It checks if two values are close enough to each other, accounting for those tiny precision errors. It's the standard approach for reliably comparing float results. You should use this function whenever you're checking the outcome of a calculation that might have floating-point inaccuracies, like finding a square root.
Real-world applications
Beyond the mechanics, functions like math.sqrt() are fundamental to solving practical problems in fields from geometry to data analysis.
Calculating distance between points with math.sqrt()
The math.sqrt() function is central to the distance formula, which applies the Pythagorean theorem to find the straight-line distance between two points.
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 snippet demonstrates how to calculate the distance between two points defined as tuples. The logic breaks down a geometric formula into simple steps:
- First, it finds the horizontal and vertical distances by subtracting the coordinates, like
point2[0] - point1[0]. - Next, it squares each of these results using the exponentiation operator (
**2). - Finally, it adds the squared values together and passes the sum to
math.sqrt()to get the final distance.
This shows how you can combine tuple indexing with mathematical functions for spatial calculations.
Computing standard deviation using math.sqrt()
In statistics, math.sqrt() is essential for calculating the standard deviation, which measures how spread out the values in a dataset are from their average.
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 snippet calculates the standard deviation, a common measure of how spread out a dataset is. The process is broken down into clear, sequential steps:
- First, the
mean(average) of thedatais found usingsum()andlen(). - Next, the
varianceis calculated. This is the average of the squared differences from the mean for each data point. - Finally,
math.sqrt()is called on thevarianceto get the standard deviation, which is then printed.
Get started with Replit
Turn your knowledge into a real tool with Replit Agent. Describe what you want, like "build a distance calculator for two points" or "create a standard deviation tool for a dataset."
The agent writes the code, tests for errors, and deploys your app from a simple prompt. Start building with Replit.
Create and deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.
Create & deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.



