How to Calculate the Square Root in Python: Multiple Approaches
--
The square root of a number x is the number y whose square is equal to x. In mathematics, the square root is represented by “√”.
In this tutorial, we will see how to calculate the square root of a number in Python using multiple approaches.
You can use several Python modules to calculate the square root of a number and you can also define your own function to calculate the square root.
Let’s get started.
How Do you Find the Square Root in Python?
The math module gives access to a wide range of mathematical functions. You don’t need to install this module separately because it is already part of the Python installation. Use the sqrt() function of the math module which returns the square root of a number.
import math
square_root = math.sqrt(49)
print(square_root)
Output:
7.0
After importing the math module, we call the sqrt() function and pass a number to it. This function returns the square root of the number passed to the function.
Note that we are passing an integer value, we can also pass a float value.
import math
square_root = math.sqrt(10.5)
print(square_root)
Output:
3.24037034920393
The value returned by the math.sqrt() function is still a float.
How Can You Calculate the Square Root of a Python List?
Python has some very powerful data types and one of them is the list. Lists are used to store multiple values in a single variable, they are ordered and mutable. You can define lists using square brackets.
Let’s see what happens if we use the Python math module to calculate the square root of a list…
import math
numbers = [10, 20, 30.50, 40.30, 50.80]
square_root = math.sqrt(numbers)
print(square_root)
When you execute this code you get the following exception that says that the math sqrt() function doesn’t support lists as input.
Traceback (most recent call last)…