To calculate the square root in Python, you can use either the math.sqrt()
function from the math
module or the exponentiation operator **
. Here’s how you can do it:
1. Using math.sqrt()
The math.sqrt()
function is the most common and straightforward way to calculate the square root.
import math
# Example
number = 16
square_root = math.sqrt(number)
print(f"The square root of {number} is {square_root}")
Output:
The square root of 16 is 4.0
2. Using the Exponentiation Operator (**
)
You can calculate the square root by raising the number to the power of 0.5
.
# Example
number = 16
square_root = number ** 0.5
print(f"The square root of {number} is {square_root}")
Output:
The square root of 16 is 4.0
3. Using pow()
The pow()
function can also be used to calculate the square root by setting the exponent to 0.5
.
# Example
number = 16
square_root = pow(number, 0.5)
print(f"The square root of {number} is {square_root}")
Output:
The square root of 16 is 4.0
4. Handling Negative Numbers
The above methods will raise a ValueError
if you try to calculate the square root of a negative number. To handle negative numbers, use the cmath
module (complex math), which supports complex numbers.
import cmath
# Example
number = -16
square_root = cmath.sqrt(number)
print(f"The square root of {number} is {square_root}")
Output:
The square root of -16 is 4j
Which Method Should You Use?
- Use
math.sqrt()
for real numbers. - Use
cmath.sqrt()
for complex numbers. - Use the
**
operator orpow()
for a concise alternative when importing modules isn’t preferred.