;

Python Program to Find the Square Root


Tutorialsrack 22/04/2020 Python

In this python program, we will learn how to find the square root of the number using the exponent operator and cmath module. In this program, we take the input from the user and store the number in the num variable and find the square root of a number using the ** exponent operator. This program works for all positive real numbers.

Program 1 - To Find the Square Root for All Positive Number
# Python Program to Find the Square Root of a Number
# For All Positive Numbers This Program works Well

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

num_sqrt = num ** 0.5
print('The square root of %0.3f is %0.3f'%(num ,num_sqrt))
Output

Enter a number: 8

The square root of 8.000 is 2.828

 

Enter a number: 64

The square root of 64.000 is 8.000

The above program works for all positive numbers. But for negative or complex numbers, we use the sqrt() function which belongs to the cmath (complex math) module.

Program 2 - For real or complex numbers
# Python Program to Find the square root of real or complex numbers

# Importing the complex math module
import cmath

#num = 5+6j

# To take input from the user
num = eval(input('Enter a number: '))

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

Enter a number: 5+6j

The square root of (5+6j) is 2.531+1.185j

Look here for more about string formatting in Python.


Related Posts



Comments

Recent Posts
Tags