How to Find Square Root in Python: Techniques Explained

By Pavan Vadapalli

Updated on Oct 13, 2025 | 18 min read | 13.99K+ views

Share:

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! 

The Easiest Way: Using Python's math.sqrt() Function 

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. 

Key Characteristics of math.sqrt(): 

  • Requires Import: To use this function, you must first import the math module. 
  • Returns a Float: It always returns the result as a floating-point number (a number with a decimal point), even if the input is a perfect square. 
  • Handles Positive Numbers and Zero: It works perfectly for any positive number or zero. 
  • Raises an Error for Negative Numbers: The math.sqrt() function cannot handle negative numbers because the square root of a negative number is not a real number. If you pass a negative number to it, Python will raise a ValueError. 

How to Use 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. 

Code Examples 

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

360° Career Support

Executive PG Program12 Months
background

Liverpool John Moores University

Master of Science in Machine Learning & AI

Double Credentials

Master's Degree18 Months

The Power of Exponents: Using the ** Operator and pow() Function 

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. 

Method 1: The Exponentiation Operator (**) 

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 

Code Examples 

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. 

Method 2: The Built-in pow() Function 

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) 

Code Examples 

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 

Comparison Table: math.sqrt() vs. ** and pow() 

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. 

For Advanced Math: The numpy.sqrt() Function 

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] 

Why Use numpy.sqrt()? 

  • Vectorization: It can compute the square root of multiple numbers in a single operation, which is significantly faster than using a Python loop with math.sqrt(). 
  • Broad Compatibility: It seamlessly works with various numeric types and data structures like Python lists and NumPy arrays. 
  • Consistency: It's part of the extensive NumPy ecosystem, making it a natural choice when you're already using the library for other numerical operations. 

How to Use numpy.sqrt() 

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!) 

Building from Scratch: Creating a Square Root Program in Python 

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 Logic of the Babylonian Method 

The algorithm works as follows: 

  1. Start with a number (num) for which you want to find the square root. 
  2. Make an initial guess. A simple and effective guess is to take half of the number (guess = num / 2). 
  3. Refine the guess. Repeatedly update the guess using the following formula: new_guess = (guess + num / guess) / 2 
  4. Repeat. Continue this process. With each iteration, new_guess becomes a more accurate approximation of the square root. 
  5. Stop when the difference between the old guess and the new guess is very small, meaning we've reached a satisfactory level of precision. 

Also Read: Why Learn Python – Top 10 Reasons to Learn Python in 2024 

Implementing the Square Root Program in Python 

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. 

Why Build Your Own? 

  • Learning: It solidifies your understanding of loops, functions, and algorithms. 
  • Customization: You have complete control. You could modify the algorithm, for instance, to find cube roots or other n-th roots. 
  • No Dependencies: The code is self-contained and doesn't require any external libraries or imports. 

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

Promise we won't spam!

Comparing the Methods: Which Square Root Technique to Choose? 

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. 

Quick Summary Table 

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) 

Detailed Breakdown and Recommendations 

1. For Simplicity and Clarity: math.sqrt() 

If your task involves finding the square root of a single, positive real number, math.sqrt() is the gold standard. 

  • When to use it: In standard applications, scripts, and anywhere you need a clear, readable, and efficient way to get the square root of a number in python. Its name explicitly states its purpose, making your code easy for others to understand. 
  • When to avoid it: If you anticipate needing to calculate the square root of negative numbers or if you are working with lists or arrays of numbers. 

2. For Flexibility and No Imports: ** or pow() 

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. 

  • When to use it: In short scripts, one-liners, or mathematical formulas where using an operator feels more natural. It's also your go-to method if you need to work with complex numbers without importing the cmath module. 
  • When to avoid it: In performance-critical applications involving large datasets, as it is not as fast as NumPy for bulk operations. 

3. For Data Science and Performance: numpy.sqrt() 

If you are working with numerical data in arrays, vectors, or matrices, there is no better choice than numpy.sqrt(). 

  • When to use it: Anytime you are using the NumPy library for tasks in data analysis, machine learning, scientific computing, or any situation requiring calculations on large datasets. Its ability to perform element-wise operations on arrays is a massive performance advantage. 
  • When to avoid it: If you're only calculating the square root of a single number in a simple script. Importing the entire NumPy library for just one calculation is unnecessary overhead. 

Also Read: Step-by-Step Guide to Learning Python for Data Science 

4. For Learning and Control: Custom Program 

Building your own square root program in Python is less about practical application and more about the educational journey. 

  • When to use it: In academic settings, coding interviews to demonstrate your problem-solving skills, or when you need to implement a highly specialized version of a root-finding algorithm. 
  • When to avoid it: In any production code where reliability, speed, and accuracy are critical. The built-in and library functions are heavily optimized and tested. 

By understanding the trade-offs, you can confidently select the most appropriate method for any challenge. 

Conclusion 

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. 

If you want to deepen your Python skills and apply them to fields like data analysis, finance, and engineering, enroll in upGrad’s DBA in Emerging Technologies with Concentration in Generative AI. Master the techniques behind intelligent, data-driven applications. Start today!

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.

In-demand Machine Learning Skills

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.

Frequently Asked Questions (FAQs)

1. What is the fastest way to find the square root in Python?

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. 

2. How do I calculate the square root of a complex number?

 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. 

3. Can I find the integer square root of a number?

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. 

4. What happens if I try numpy.sqrt() on a negative number?

 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. 

5. Is there a difference in precision between the methods?

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. 

6. How can I handle errors when a user inputs a negative number?

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. 

7. How do I calculate the cube root in Python?

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. 

8. Why does (-9)**0.5 give a complex number but math.sqrt(-9) gives an error?

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. 

9. Can I use numpy.sqrt() without installing the full NumPy library?

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. 

10. What is a "domain error" in math.sqrt()?

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. 

11. Is pow(x, 0.5) ever better than x ** 0.5?

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. 

12. How does the Babylonian method (Heron's method) work intuitively?

 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. 

13. What is the difference between a float and a numpy.float64?

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. 

14. Can I find the square root of a pandas Series or DataFrame?

 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. 

15. How do I format the square root result to a specific number of decimal places?

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. 

16. Are there other numerical algorithms to calculate square roots?

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. 

17. Why is math.isqrt() faster for integer square roots?

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. 

18. What if I provide a non-numeric input to a square root function?

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. 

19. How does Python handle the square root of infinity?

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. 

20. Can I create a lambda function to calculate square roots?

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. 

Pavan Vadapalli

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

+91

By submitting, I accept the T&C and
Privacy Policy

India’s #1 Tech University

Executive Program in Generative AI for Leaders

76%

seats filled

View Program

Top Resources

Recommended Programs

LJMU

Liverpool John Moores University

Master of Science in Machine Learning & AI

Double Credentials

Master's Degree

18 Months

IIITB
bestseller

IIIT Bangalore

Executive Diploma in Machine Learning and AI

360° Career Support

Executive PG Program

12 Months

upGrad
new course

upGrad

Advanced Certificate Program in GenerativeAI

Generative AI curriculum

Certification

4 months