Python program to find square root of a number

In this program, we will calculate the square root of a number by writing some code in python.

Square root of a number is a number that when multiplied by itself results in the original number.
For example Square root of 9 is 3 because 3 * 3 = 9

To understand this example, you should have the knowledge of following topics in python.

  • Python Operators
  • Python data types
  • input/output
  • import statement

Program by choosing a number manually

This example is for positive numbers and is made by using the exponent operator. An exponent operator in python is used to raise the number on the left hand side to the power of the exponent of the right hand side.
For example 5 ** 4 = 625

# Program to find the square root
num = 9
square_root = num ** 0.5
print('The square root of {} is'.format(num), square_root)

Output

The square root of 9 is 3.0

Program by taking user input

num = int(input("Enter a number"))
square_root = num ** 0.5
print('The square root of {} is'.format(num), square_root)

Output

Enter a number 12

The square root of 12 is 3.4641016151377544

Program by using inbuilt function

There is a library in python named as cmath. It has a function named sqrt, which is used to calculate the square root of number. Before using this function, we need to import the cmath library.

import cmath
num = 9
square_root = cmath.sqrt(num)
print('The square root of {} is'.format(num), square_root)

Output

The square root of 9 is 3.0

Program to find the square root of a real or complex numbers

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

Output

The square root of (1+2j) is 2.000+1.000j