Python Square Root – The sqrt() Function with Examples

How to find the square root using the Python sqrt() function

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

Syntax of the sqrt() Function

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

math.sqrt(number)

Argument

  • Number: The number for which you want to find the square root

Remarks

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

Square Root Examples

Example 1: Find the square root of 4

The following example is a sample program that finds the square root of 4:

  1. import math
  2. #find the square root of 4
  3. square_root = math.sqrt(4)
  4. print("The square root of 4 is", square_root)

Output:

The square root of 4 is 2.0

Example 2: Find the square root of 5

Below is a sample program that finds the square root of 5:

  1. import math
  2. #find the square root of 5
  3. square_root = math.sqrt(5)
  4. print("The square root of 5 is", square_root)

Output:

The square root of 5 is 2.23606797749979

Example 3: Find the square root of -5

Below is a sample program to find the square root of -5:

  1. import math
  2. #find the square root of -5
  3. square_root = math.sqrt(-5)
  4. print("The square root of -5 is", square_root)

Output:

ValueError: math domain error

The number -5 is a negative value, so Python produces an error.

Example 4: Find the square root without using sqrt()

The following is a sample program that finds the square root of a number without using any built-in functions.

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

Output:

The square root of 25 is 5.0

Summary

In this tutorial, you learned how to find the square root of a number using Python's sqrt() function. This tutorial also showed how to find the square root without using Python's sqrt().


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