Square root of a number in Python

In this article, we would discuss how to find the square root a number in Python. First, it would be through a program. In the latter part of the article, we would do it using math module. But, there’s a catch. We can’t find it (sqrt) for a negative number using math module in Python or through our program.

If you want to see how to find the square root of a negative number.

Note: Python v3.9 was used to get the desired outcome below.

Square root of a number in Python through a program

This is the summary of what we are going to execute next –

  1. Get a float input from the user,
  2. Multiply the float input with 0.5,
  3. Store the result of step 2 in a variable (or, the outcome),
  4. Print the outcome.

Here is the Python program –

#Program to calculate the square root a number
x = float(input('Enter a number: '))
o = x ** 0.5
print("The square root the number ",x," is: ", o)

Lets say the user enters a number: 9

Output –

The square root the number 9.0 is: 3.0

Square root of a number in Python using math module

Alternately, we can get the desired outcome using math module. Therefore, first import the math module. This way we get to use the sqrt() function available through math module.

So,

import math
x = float(input('Enter a number: '))
o = math.sqrt(x)
print("The square root the number ",x," is: ", o)

The user input: 9

Output –

The square root the number 9.0 is: 3.0

Pretty similar to we what we did before. Now, consider a scenario where the user enters a negative input: -9

It would throw an error –

ValueError: math domain error

To make sure it doesn’t happen, we may warn user for a negative input beforehand or use if statement;

import math
x = float(input('Enter a number: '))
if (x>0):
        o = math.sqrt(x)
        print("The square root the number ",x," is: ", o)
else:
        print("Warning: It should be a non-negative input")

In conclusion, we have discussed how to find the square root of a non-negative input in Python.

Similar Posts