ScanSkill

Square Root of a Number in Python

In this, we'll write some example programs to find the square root of a number in Python using different approaches.

This covers following approaches:

  • Find the square root of a number in Python using ** operator
  • Find the square root of a number in Python using math.sqrt() inbuilt function
  • Find the square root of a number in Python using math.pow()
  • Find the square root of a number in Python using a user-defined function
  • Find the square root of a number in Python using class

Prerequisites

Square root of a number in Python using ** operator

This program asks the user to input a number whose square root is going to be calculated. Then the ** operator is used to calculate the square root of the number.

print("Enter a Number: ")
num = int(input())

squareroot = num ** 0.5

print(f"The square Root of {num} = {squareroot}")

Here, num**0.5 returns num1/2, i.e. if the user input is 9 then the num**0.5 = 91/2 = 3.

Output:

Enter a Number: 
9
Square Root of 9 = 3.0

Square root of a number in Python using math.pow()

This program does the same task i.e. square root of a number, but using pow() function.

import math

print("Enter a Number: ")
num = int(input())

squareroot = math.pow(num, 0.5)
print(f"The square root of {num} = {squareroot}")

Output:

Enter a Number: 
9
Square Root of 9 = 3.0

Square root of a number in Python using function

In this approach, a function square_root() takes an argument and evaluates square root. The function is called after user input.

def square_root(n):
  return n ** 0.5

print("Enter a Number: ")
num = int(input())

squareroot = square_root(num)
print(f"The square root of {num} = {squareroot}")

Output:

Enter a Number: 
9
Square Root of 9 = 3.0

Square root of a number in Python using Class

class SquareRootCalculate:
  def square_root(self, n):
    return n ** 0.5

print("Enter a Number: ")
num = int(input())

obj1 = SquareRootCalculate()
squareroot = obj1.square_root(num)
print(f"The square root of {num} = {squareroot}")

Here, all properties of the class named SquareRootCalculate get assigned to an object named obj1. Then the object can be used to access the member function of the class SquareRootCalculate using the dot (.) operator. (vc_obj.square_root(num))

Output:

Enter a Number: 
9
Square Root of 9 = 3.0

Conclusion

In this, we discussed find and print square root of a number in Python using **, using math.pow() function, using user-defined function and using class.