Python Program to Find Square Root
In this tutorial you will learn to write a simple Python program to find the Square Root of a Positive number, Real and Complex numbers.
Find the Square Root for Positive Numbers
Here we are using the exponent operator to find square root for positive numbers. This method can't be used for negative or complex numbers.
Python Example Program
1 # Python Program to calculate the square root
2
3 # Read the Positive number from the user
4 number = float(input('Enter a positive number: '))
5
6 # Calculate the Square Root
7 number_sqrt = number ** 0.5
8
9 # Display Result
10 print('The square root of %0.2f is %0.2f'%(number ,number_sqrt))
Program Output : Run 1
Enter a positive number: 25
The square root of 25.00 is 5.00
Program Output : Run 2
Enter a positive number: 625
The square root of 625.00 is 25.00
Program Output : Run 3
Enter a positive number: 100
The square root of 100.00 is 10.00
Program Output : Run 4
Enter a positive number: 1
The square root of 1.00 is 1.00
Find the Square Root for Real or Complex Numbers
Here we are using the Complex Math module to calculate the square root.
Python Example Program
1 # Find square root of real or complex numbers
2
3 # Import the complex math module
4 import cmath
5
6 # Take input from the user
7 # We have to use eval() to get complex number as input directly.
8 number = eval(input('Enter a number: '))
9
10 # Compute Square Root
11 number_sqrt = cmath.sqrt(number)
12
13 # Display Result
14 # Values are displayed with 2 decimal places here
15 print('The square root of {0} is {1:0.2f}+{2:0.2f}j'
16 .format(number ,number_sqrt.real,number_sqrt.imag))
Program Output : Run 1
Enter a number: 2+3j
The square root of (2+3j) is 1.674+0.896j
Note : We have to use eval() to get complex number as input directly from the user.