The square root of a number x is a value y such that when y is multiplied by itself, it equals x.
- Mathematical Representation: √x = y where y × y = x
- For Example: √25 = 5 because 5 × 5 = 25
Python has several methods to find the square root of a number. Here are a few common approaches, each with an explanation and example.
Each method has its use case, depending on whether you’re working with simple numbers, complex numbers, or more advanced mathematical operations.
1. Using the Exponentiation Operator (**)
The ** operator in Python is the exponentiation operator, used to raise a number to a power (e.g., a ** b computes a^b). This is the simplest method in Python for calculating the square root of a given number. The square root of a number is equivalent to raising the number to the power of 0.5.
Code Example
Output
# Enter a number: 0 # The square root of 0.0 is 0.0 # Enter a number: 64 # The square root of 64.0 is 8.0 # Enter a number: 3.5 # The square root of 3.5 is 1.8708286933869707 # Enter a number: -64 # The square root of -64.0 is (4.898587196589413e-16+8j)
Explanation
- Here, we are taking the number as input from the user. And converting it to the float.
- The expression
num ** 0.5calculates the square root by raising the number to the power of 0.5. - Note: This calculation does not work for negative numbers. In case of a negative number, it gives an invalid answer.
2. Using math.sqrt() Function
math.sqrt() is a function in Python’s math module that returns the square root of a given non-negative number. This method is helpful because it’s a dedicated function for this operation and ensures precision.
Syntax – math.sqrt(x)
- It takes one argument (a number) and returns the square root.
xmust be non-negative (x ≥ 0).- Returns a floating-point value.
- Raises a
ValueErrorifxis negative.
Code Example
Output
square root of 0: 0.0
square root of integer number 4: 8.0
square root of float number 5.6: 2.3664319132398464
3: Using cmath.sqrt() Function for complex numbers
To calculate the square root of a number in Python the cmath module can be used when dealing with both real and complex numbers. It is useful for finding square roots of negative numbers.
Code Example
Output:
square root of integer number 64: (8+0j)
square root of float number 5.6: (2.3664319132398464+0j)
square root of negative number -64: 8j
Explanation
cmath.sqrt()can handle both real and complex numbers.- If the input is negative, this function returns a complex number as the square root.
- For example,
cmath.sqrt(-144)returns 12j andcmath.sqrt(144)returns 12+0j - In Python,
12+0jand12jare both complex numbers, but they represent different values.12+0j: This is a complex number with a real part of 12 and an imaginary part of 0.12j: This is a purely imaginary number with no real part and an imaginary part of 12.

Leave a Reply