Home » Programming » Python Program to Find the Square Root

# Python Program to Find the Square Root

In this post, we will be investigating the Python Program to Find the Square Root. We will find the square root and clarify the linguistic structure simply referred to as syntax of the program.

## Algorithm to find the square root

Here, we will store the value of a number in variable num. After that, we will make use of one among the arithmetic operators available in Python and that is (`**`) exponentiation operator to find the square root.

We will also place a second variable named num_sqrt to store the final value of square root.

``````Step 1: Start
Step 2: Take input in variable num
Step 3: Find square by exponential of num by 0.5 and assign it to num_sqrt
i.e. num_sqrt = num ** 0.5
Step 4: End ``````

New to Python Programming? Get started with Python Programming!

The above mentioned algorithm works perfectly for all positive real numbers. But for negative or complex numbers; we need to import cmath (complex math) library (shown in example 3).

## Find Square Root in Python

Focusing on the Python program to find the square root, let’s go with the following examples investigating the possible cases.

### Example 1: For positive numbers

```num = 7

# Find exponential of num by 0.5
num_sqrt = num ** 0.5
print("The square root of %0.3f is %0.3f"%(num, num_sqrt))
```

Note: We find the exponential of num by 0.5 by because the power of square root is 1/2 and the decimal value of 1/2 is 0.5.

The output of above code snippet is,

``The square root of 7.000 is 2.646 ``

### Example 2: For positive numbers with user input

```num = float(input("Enter a number: "))

# Find exponential of num by 0.5
num_sqrt = num ** 0.5
print("The square root of %0.3f is %0.3f"%(num, num_sqrt))```

Note: We converted the type of num to float as the `input()` takes the input in a string type; so in order to make it numerical we need to convert that.

The output of above code snippet is,

``````Enter a number: 7
The square root of 7.000 is 2.646``````

### Example 3: For complex numbers

Here, for the complex numbers we need to use `sqrt()`function which can be invoked from `cmath` (complex math) library.

```# Importing the complex math library
import cmath

num = 2+3j

num_sqrt = cmath.sqrt(num)
print("The square root of {0} is {1:0.3f}+{1:0.3f}j".format(num, num_sqrt.real, num_sqrt.imag))```

The output for above code snippet is,

``The square root of (2+3j) is 1.674+1.674j``

### Example 4: For complex numbers with user input

```# Importing the complex math library
import cmath

num = eval(input("Enter a complex number: "))

num_sqrt = cmath.sqrt(num)
print("The square root of {0} is {1:0.3f}+{1:0.3f}j".format(num, num_sqrt.real, num_sqrt.imag))```

Note: For taking the complex number as input we have to use `eval()`function. The `eval()`method can be used to convert complex numbers as input to complex numbers in Python.

You can also check —>