Python Square Root – The sqrt() Function with Examples

How to Find a Square Root using the sqrt() Function in Python

In this tutorial, you'll learn how to use the sqrt() function to find a square root of a number in Python. This tutorial also shows you how to find a square root without using the Python sqrt() function.

Syntax of the sqrt() Function

The syntax of the sqrt() function is as follows:

math.sqrt(number)

Argument

  • number: The number that you want to find a square root

Remarks

  • To use the sqrt() function, you need to import the math module.
  • The number argument must be positive.

Square Root Examples

Example 1: Find a Square Root of 4

The following example illustrates a sample program to find a square root of 4:

import math
#find a square root of 4
square_root = math.sqrt(4)
print("The square root of 4 is", square_root)

Result:

The square root of 4 is 2.0

Example 2: Find a Square Root of 5

The following is a sample program to find a square root of 5:

import math
#find a square root of 5
square_root = math.sqrt(5)
print("The square root of 5 is", square_root)

Result:

The square root of 5 is 2.23606797749979

Example 3: Find a Square Root of -5

The following is a sample program to find a square root of -5:

import math
#find a square root of 5
square_root = math.sqrt(-5)
print("The square root of -5 is", square_root)

Result:

ValueError: math domain error

As you can see, since the number -5 is a negative value, Python issues an error.

Example 4: Find a Square Root without Using sqrt()

The following is a sample program to find a square root of a number without using any built-in functions:

import math
#find a square root of 25 without using math module (sqrt)
square_root = 25**(1/2)
print("The square root of 25 is", square_root)

Result:

The square root of 25 is 5.0

In this tutorial, you've learned how to find a square root of a number using the Python sqrt() function. You also have learned how to find a square root of a number without using sqrt() in Python.


See also:
Python return Statement with Examples
Python List Methods and Functions with Examples
Python abs() – Absolute Value in Python
Python Factorial – Find the Factorial of a Number
Python min() – Find the Smallest Value in Python

Leave a Comment