Find the Square Root of a Number

In this Python lesson, we will practice how to write a program to find the square root of a number. We are going to carry out this practice using the exponent operator for positive numbers and the cmath module for complex numbers respectively.

Example 1: Find the Square Root of a Positive Number

# Request input from the user
num = float(input('Enter a number: '))

sqrt = num ** 0.5
print('The square root of %0.2f is %0.2f'%(num ,sqrt))

Output

Enter a number: 64

The square root of 64.00 is 8.00

In the program above, we used the ** exponent operator to find the square root of any number stored in the num variable entered by the user. The above program is used only for positive numbers while for negative or complex numbers, we use the cmath to find the square root.

Practice B: Find the Square Root of Complex Numbers

# Import the complex math module
import cmath

# Request input from the user
num = complex(input('Enter complex number: '))

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

Output

Enter complex number: 2+5j

The square root of (2, 5) is 1.92+1.30j

In the program above, we were able to find the square of a complex number using the sqrt() function in the cmath (complex math) module. You should note that whenever we want to take the complex number as input from a user, such as 2+5j, we have to use the complex() function instead of float() or int(). This method is used to convert complex numbers as input to complex objects in Python.

Do you want to become an expert programmer? See books helping our students, interns, and beginners in software companies today (Click here)!

Leave a Comment

Python Tutorials