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:
import math #find the square root of 4 square_root = math.sqrt(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:
import math #find the square root of 5 square_root = math.sqrt(5) 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:
import math #find the square root of -5 square_root = math.sqrt(-5) 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.
import math #find the square root of 25 without using math module (sqrt) square_root = 25**(1/2) 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().