How to Find Square Root in Python: Techniques Explained
Updated on Oct 13, 2025 | 18 min read | 13.99K+ views
Share:
For working professionals
For fresh graduates
More
Updated on Oct 13, 2025 | 18 min read | 13.99K+ views
Share:
Table of Contents
Did you know? Rabin cryptosystem, used for encryption in your online messages, relies on complex square root problems to protect data, making it incredibly difficult to hack. Thanks to Python’s powerful math tools, your information remains safe and secure! |
Finding the square root in Python is simple and can be done using several techniques. You can use built-in functions like math.sqrt(), operators like **, or libraries such as NumPy and SymPy for advanced use cases. Each method offers different levels of precision and flexibility depending on whether you’re working with single numbers, arrays, or symbolic computations.
In this detailed guide, you will learn everything you need to know about how to find square root in Python. We will explore various techniques, starting with the simplest methods and progressing to more advanced applications. You will see practical code examples, understand the differences between each approach, and learn how to write your very own square root program from the ground up. By the end, you'll be able to confidently implement the best method for any scenario you encounter.
Boost your career with Online Data Science Courses, by upGrad now featuring a GenAI-integrated curriculum. Learn from top faculty at IIIT Bangalore and LJMU with globally recognized certification. Master Python, Machine Learning, AI, SQL, and Tableau — all built for real-life impact!
For most day-to-day tasks, the simplest and most direct method to find the square root of a number in Python is by using the sqrt() function from the built-in math module. A module in Python is essentially a file containing a set of functions and definitions that you can use in your code. The math module is a standard library that provides access to a wide range of mathematical functions.
The math.sqrt() function is specifically designed for one purpose: calculating the square root. It is efficient, accurate, and very easy to use. However, it's important to know its characteristics to use it effectively.
Popular AI Programs
Key Characteristics of math.sqrt():
Let's walk through the steps to use this square root function in python.
Step 1: Import the math Module
Before you can use sqrt(), you need to tell Python that you want to use functions from the math module. You do this with an import statement at the beginning of your script.
import math
Step 2: Call the math.sqrt() Function
Once the module is imported, you can call the function using dot notation: math.sqrt(number), where number is the value whose square root you want to find.
Let's look at a few examples to see it in action.
Example 1: Finding the square root of a perfect square
import math
# Input number
num = 25
# Calculate the square root
square_root_result = math.sqrt(num)
# Print the result
print(f"The square root of {num} is: {square_root_result}")
print(f"The type of the result is: {type(square_root_result)}")
Output:
The square root of 25 is: 5.0
The type of the result is: <class 'float'>
Notice that even though 25 is a perfect square, the result is 5.0, a float, not 5, an integer.
Example 2: Finding the square root of a non-perfect square
import math
# Input number
num = 18
# Calculate the square root
square_root_result = math.sqrt(num)
print(f"The square root of {num} is: {square_root_result}")
Output:
The square root of 18 is: 4.242640687119285
Example 3: What happens with a negative number?
If you try to find the square root of a negative number, math.sqrt() will stop your program and show an error.
import math
# Input number
num = -16
# This line will cause an error
try:
square_root_result = math.sqrt(num)
print(f"The square root of {num} is: {square_root_result}")
except ValueError as e:
print(f"Error: {e}")
Output:
Error: math domain error
This ValueError is Python's way of telling you that the input is outside the valid domain of the function for real numbers. For handling complex numbers, you'll need a different module, like cmath, which we'll touch upon later.
Using math.sqrt() is the most common and Pythonic way for how to find square root in Python for real numbers.
Also Read: Top 7 Data Types in Python: Examples, Differences, and Best Practices (2025)
Machine Learning Courses to upskill
Explore Machine Learning Courses for Career Progression
Another versatile way to calculate the square root of a number in Python involves using the principles of exponentiation. Mathematically, the square root of a number x is equivalent to raising x to the power of 0.5 (or 1/2). This concept can be directly translated into Python code using two primary methods: the exponentiation operator ** and the built-in pow() function.
These methods are incredibly useful because they don't require any module imports and offer more flexibility in handling different types of numbers, including negative ones, which result in complex numbers.
The ** operator is Python's standard operator for raising a number to a power. It's concise, readable, and a favorite among many developers for its simplicity.
Syntax: number ** 0.5
Example 1: Finding the square root of a positive number
This works just like math.sqrt() but without the need for an import statement.
# Input number
num = 64
# Calculate the square root using the ** operator
square_root_result = num ** 0.5
print(f"The square root of {num} is: {square_root_result}")
print(f"The type of the result is: {type(square_root_result)}")
Output:
The square root of 64 is: 8.0
The type of the result is: <class 'float'>
Example 2: Handling negative numbers
Unlike math.sqrt(), the ** operator can compute the square root of a negative number, returning a complex number as the result. A complex number has a real part and an imaginary part (denoted by j in Python).
# Input number
num = -64
# Calculate the square root
# The result will be a complex number
square_root_result = num ** 0.5
print(f"The square root of {num} is: {square_root_result}")
print(f"The type of the result is: {type(square_root_result)}")
Output:
The square root of -64 is: (4.898587196589413e-16+8j)
The type of the result is: <class 'complex'>
The real part is a very small number close to zero due to floating-point arithmetic, and the imaginary part is 8j.
Python also has a built-in pow() function that achieves the same result. The pow(base, exponent) function is another way to perform exponentiation.
Syntax: pow(number, 0.5)
Example 1: Finding the square root of a positive number
# Input number
num = 81
# Calculate the square root using the pow() function
square_root_result = pow(num, 0.5)
print(f"The square root of {num} is: {square_root_result}")
Output:
The square root of 81 is: 9.0
The pow() function and the ** operator are functionally equivalent for this purpose. The choice between them often comes down to coding style and readability. Some find the ** operator more direct, while others prefer the explicit function call of pow().
Also Read: Precedence of Operators in Python: Complete Guide with Examples
Feature |
math.sqrt() |
** 0.5 Operator |
pow(number, 0.5) |
Module Import | Requires import math | None needed | None needed |
Return Type | Always float | float for positive input, complex for negative input | float for positive input |
Handling Negative Numbers | Raises ValueError | Returns a complex number | Can return a complex number (e.g., pow(-64, 0.5)) |
Readability | Very clear intent (sqrt) | Concise mathematical notation | Explicit function call |
Use Case | Best for real-number mathematics where clarity is key. | Great for general calculations and when complex numbers might arise. | A clear alternative to ** based on preference. |
Using exponents is a powerful technique for how to find square root in Python, offering a built-in solution that is both flexible and efficient.
When you venture into the fields of data science, machine learning, or scientific computing, you'll almost certainly encounter the NumPy library. NumPy (Numerical Python) is the fundamental package for numerical computation in Python. It provides a powerful object called an array, which is a grid of values, and a vast collection of functions to operate on these arrays efficiently.
Among its many functions is numpy.sqrt(), a superior alternative for numerical tasks that involve collections of numbers, such as lists or arrays. This square root function in python is designed for performance and can apply the square root operation to every element of an array at once, a process known as vectorization.
Also Read: Numpy Array in Python [Everything to know]
First, you need to have NumPy installed. If you don't have it, you can install it using pip:
pip install numpy
Step 1: Import the NumPy Library
The standard convention is to import NumPy with the alias np to keep your code concise.
import numpy as np
Step 2: Apply np.sqrt() to Your Data
You can pass a single number, a list, or a NumPy array to the np.sqrt() function.
Code Examples
Example 1: Square root of a single number
It works similarly to math.sqrt() for a single number.
import numpy as np
num = 144
# Calculate the square root
square_root_result = np.sqrt(num)
print(f"The square root of {num} is: {square_root_result}")
print(f"The type of the result is: {type(square_root_result)}")
Output:
The square root of 144 is: 12.0
The type of the result is: <class 'numpy.float64'>
Note the result's type is a NumPy-specific float, which offers more precision.
Example 2: Square root of a Python list
This is where numpy.sqrt() starts to shine. It takes the list, converts it into a NumPy array, performs the operation, and returns the result as a new NumPy array.
import numpy as np
numbers_list = [4, 9, 16, 25, 30]
# Calculate the square root for all elements in the list
square_root_results = np.sqrt(numbers_list)
print(f"Original list: {numbers_list}")
print(f"Square roots: {square_root_results}")
print(f"The type of the result is: {type(square_root_results)}")
Output:
Original list: [4, 9, 16, 25, 30]
Square roots: [2. 3. 4. 5. 5.47722558]
The type of the result is: <class 'numpy.ndarray'>
Example 3: Square root of a multi-dimensional NumPy array
numpy.sqrt() can handle arrays of any shape and size, which is incredibly powerful for image processing or scientific simulations.
import numpy as np
# Create a 2x3 NumPy array (2 rows, 3 columns)
matrix = np.array([[1, 2, 3], [4, 5, 6]])
# Calculate the square root of each element
square_root_matrix = np.sqrt(matrix)
print("Original matrix:")
print(matrix)
print("\nSquare root of the matrix:")
print(square_root_matrix)
Output:
Original matrix:
[[1 2 3]
[4 5 6]]
Square root of the matrix:
[[1. 1.41421356 1.73205081]
[2. 2.23606798 2.44948974]]
For anyone working with numerical data in bulk, numpy.sqrt() is the undeniable choice for how to find square root in Python. Its performance and ability to handle arrays make it an indispensable tool.
Also Read: How to Install Python in Windows (Even If You're a Beginner!)
While Python's built-in functions and libraries are incredibly efficient, building a square root program in Python from scratch is an excellent exercise to deepen your understanding of programming logic and numerical algorithms. It allows you to see what's happening "under the hood" and appreciate the computational thinking behind finding a square root.
We will use a popular and ancient algorithm known as the Babylonian method, also called Heron's method. It's an iterative approach that starts with an initial guess and refines it step-by-step until it gets closer and closer to the actual square root.
The algorithm works as follows:
Also Read: Why Learn Python – Top 10 Reasons to Learn Python in 2024
Let's turn this logic into a Python function. Our function will take the number and a tolerance level (how close we want to get to the answer) as inputs.
def custom_square_root(number, tolerance=1e-7):
"""
Calculates the square root of a number using the Babylonian method.
Args:
number (float or int): The number to find the square root of. Must be non-negative.
tolerance (float): The desired precision of the result.
Returns:
float: The approximate square root of the number.
"""
# Handle invalid input
if number < 0:
raise ValueError("Cannot calculate the square root of a negative number.")
if number == 0:
return 0
# Step 2: Make an initial guess
guess = number / 2.0
# Loop until the guess is accurate enough
while True:
# Step 3: Refine the guess
new_guess = (guess + number / guess) / 2.0
# Step 5: Check if the guess has converged
if abs(new_guess - guess) < tolerance:
return new_guess
# Update the guess for the next iteration
guess = new_guess
# --- Let's test our function ---
# Test Case 1: A perfect square
num1 = 49
sqrt1 = custom_square_root(num1)
print(f"The custom square root of {num1} is: {sqrt1}")
# Test Case 2: A non-perfect square
num2 = 50
sqrt2 = custom_square_root(num2)
print(f"The custom square root of {num2} is: {sqrt2}")
# Let's compare with math.sqrt()
import math
print(f"The math.sqrt of 50 is: {math.sqrt(50)}")
Output:
The custom square root of 49 is: 7.000000000000001
The custom square root of 50 is: 7.0710678118654755
The math.sqrt of 50 is: 7.0710678118654755
As you can see, our custom function produces a result that is extremely close to the one from the highly optimized math.sqrt() function.
While you would typically use the built-in methods for speed and reliability in production code, creating your own square root program in python is an invaluable learning experience for any aspiring programmer. It's a classic problem that elegantly demonstrates the power of computational algorithms.
Also Read: Top 36+ Python Projects for Beginners and Students to Explore in 2025
Subscribe to upGrad's Newsletter
Join thousands of learners who receive useful tips
We've explored several powerful ways for how to find square root in Python. Each method has its own strengths and is suited for different situations. Choosing the right one depends on your specific goals, such as performance, handling of different data types, or the need for external libraries.
Let's consolidate everything into a clear comparison to help you decide which technique is the best fit for your project.
This table provides a high-level overview of the key differences between the methods.
Method |
Best For |
Requires Import |
Handles Negative Numbers? |
Handles Arrays? |
math.sqrt() | General-purpose, simple, real-number calculations. | import math | No (raises ValueError) | No (one number at a time) |
** 0.5 | Quick calculations without imports; handles complex numbers. | No | Yes (returns complex) | No (one number at a time) |
pow(x, 0.5) | Alternative to ** operator based on coding style. | No | Yes (returns complex) | No (one number at a time) |
numpy.sqrt() | Data science, numerical analysis, large arrays of data. | import numpy | No (returns nan) | Yes (highly optimized) |
Custom Function | Learning algorithms, educational purposes, special cases. | No | No (unless coded to) | No (unless coded to) |
If your task involves finding the square root of a single, positive real number, math.sqrt() is the gold standard.
When you need a quick, built-in way to perform the calculation or if you need to handle potential negative inputs that should result in complex numbers, the exponentiation approach is ideal.
If you are working with numerical data in arrays, vectors, or matrices, there is no better choice than numpy.sqrt().
Also Read: Step-by-Step Guide to Learning Python for Data Science
Building your own square root program in Python is less about practical application and more about the educational journey.
By understanding the trade-offs, you can confidently select the most appropriate method for any challenge.
We've covered a wide array of techniques for how to find square root in Python, each with its unique advantages. From the simplicity of the math.sqrt() function to the raw power of numpy.sqrt() for large datasets, Python provides a tool for every need.
The right method depends entirely on your context. By understanding these options, you are now fully equipped to handle any square root calculation that comes your way, choosing the most efficient and appropriate tool for the job.
Expand your expertise with the best resources available. Browse the programs below to find your ideal fit in Best Machine Learning and AI Courses Online.
Discover in-demand Machine Learning skills to expand your expertise. Explore the programs below to find the perfect fit for your goals.
Artificial Intelligence Courses | Tableau Courses |
NLP Courses | Deep Learning Courses |
Discover popular AI and ML blogs and free courses to deepen your expertise. Explore the programs below to find your perfect fit.
For a single number, math.sqrt() is highly optimized and very fast. For calculations on a large array or list of numbers, numpy.sqrt() is significantly faster because it performs the operation in compiled C code, avoiding the overhead of a Python loop.
You should use the cmath module, which is designed for complex number mathematics. Import it and use cmath.sqrt(). For example, import cmath; cmath.sqrt(-1) will correctly return 1j. The ** 0.5 operator can also do this automatically.
Yes. If you want only the integer part of a square root, you can use math.isqrt() (available in Python 3.8+). This function is faster than int(math.sqrt(x)) because it calculates the integer square root directly without using floating-point arithmetic.
Unlike math.sqrt(), which raises a ValueError, numpy.sqrt() will not raise an error. Instead, it will return nan (Not a Number) and might show a RuntimeWarning. This is useful for handling arrays with mixed positive and negative values without crashing the program.
The precision is generally very high and comparable for math.sqrt(), ** 0.5, and numpy.sqrt(). NumPy might use a different precision float (numpy.float64) compared to standard Python floats, but for most practical purposes, the difference is negligible.
You can use a try-except block. Place the math.sqrt(number) call inside the try block and catch the ValueError in the except block. In the except block, you can print a user-friendly message or ask for a new input.
You can use the exponentiation method. The cube root of a number x is x raised to the power of 1/3. So, you can calculate it as x ** (1/3) or pow(x, 1/3). This works for any n-th root.
The math module is specifically designed for real number mathematics, where the square root of a negative number is undefined. The exponentiation operator ** is more general and defaults to the rules of complex arithmetic, where the square root of a negative number is a valid imaginary number.
No, numpy.sqrt() is an integral part of the NumPy library. You must have NumPy installed in your Python environment to use it. The library is a standard tool in the scientific Python ecosystem, and its installation is straightforward using pip.
A "math domain error" occurs when you provide a function with an input value that is outside its domain of definition. For math.sqrt(x), the domain is all non-negative real numbers (x >= 0). Providing a negative number violates this condition, hence the error.
Functionally, they are very similar for this task. The choice is mostly about style. However, the pow() function can take an optional third argument for modular exponentiation (pow(base, exp, mod)), which is a different use case altogether. For square roots, they are interchangeable.
If your current guess for the square root of a number N is g, and g is too small, then N/g will be too large. If g is too large, N/g will be too small. The method takes the average of g and N/g, which gives a new, much better guess in the middle. Repeating this quickly converges to the true root.
A standard Python float is a double-precision 64-bit floating-point number (IEEE 754 standard). A numpy.float64 is NumPy's implementation of the same. While they are fundamentally similar, NumPy's types are part of its own type system, which enables optimized C and Fortran code to operate on NumPy arrays.
Yes. Since the pandas library is built on top of NumPy, you can call numpy.sqrt() directly on a pandas Series or DataFrame. It will perform the calculation element-wise, just as it would for a NumPy array, and return a new Series or DataFrame with the results.
You can use an f-string or the round() function. For example, f"{math.sqrt(10):.2f}" will format the result to two decimal places. Alternatively, round(math.sqrt(10), 2) will round the number itself.
Yes, besides the Babylonian method, another common approach is the binary search method. If you are looking for the square root of N, you can perform a binary search for a number x in the range [0, N] such that x*x is very close to N.
Floating-point arithmetic involves complex hardware operations and can have precision issues. math.isqrt() uses integer-only arithmetic, which is computationally simpler and faster for the CPU. It avoids the overhead of converting to and from floats.
If you pass a string or another non-numeric type to any of the square root functions (math.sqrt, numpy.sqrt, etc.), Python will raise a TypeError, as these functions are designed to operate only on numbers.
Using math.sqrt(float('inf')) or numpy.sqrt(float('inf')) will correctly return infinity. The functions are designed to handle special floating-point values like infinity and NaN according to the IEEE 754 standard.
Absolutely. A lambda function provides a concise way to define a simple function. You could define square_root = lambda x: x ** 0.5. You can then call it like any other function: square_root(25) would return 5.0.
900 articles published
Pavan Vadapalli is the Director of Engineering , bringing over 18 years of experience in software engineering, technology leadership, and startup innovation. Holding a B.Tech and an MBA from the India...
Speak with AI & ML expert
By submitting, I accept the T&C and
Privacy Policy
Top Resources