In this tutorial, we’ll learn how to write a Python program to find the square root of a number using different methods. This is one of the most common Python number operation examples, useful for beginners learning Python programming.
What is a Square Root?
The square root of a number is a value that, when multiplied by itself, gives the original number.
For example:
Square root of 9 is 3, because 3 × 3 = 9.
Prerequisites
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 demonstrates how to calculate the square root using exponent operator in Python, which is ** (power operator).
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
This program demonstrates how to calculate the square root of a complex number in Python using cmath.sqrt().
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
