Python | Function to calculate the square root of a number

Let us look at the methods we have to calculate the square root of a number. Here we will use functions. In the first method, we will not pass arguments to the function and in the other method we will pass the arguments that are taken dynamically by the user the last one is using the math library

Method 1: Without arguments and static value

def square_root():
   
    num = 8 
    num_sqrt = num ** 0.5
    print('The square root of %0.3f is %0.3f'%(num ,num_sqrt))


square_root()

Output:

The square root of 8.000 is 2.828

Explanation:

Here, we simply defined a function and called it in the later part of the program. We have statically defined a variable num, whose square root we want to find. ** means Exponentiation Operator. Now in the print statement, we used %0.3f, what does this even mean?

This simply means that f is a Floating point decimal format. The .3 after f indicates to round up the digits to 3 places after the decimal point. Hence the output we got has three digits after the decimal point.

Method 2: Without arguments and dynamic values

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

num = int(input("Enter the number you want to find the square root of: "))
square_root(num)

Output:

Enter the number you want to find the square root of: 16
The square root of 16.000000 is 4.000

Explanation:

Here the difference is that we have passed arguments to the function. This is the value that we dynamically took from the user and passed it on to the function. Another difference is that we have removed %0.3f, so what will happen is that Python will print 6 digits after the decimal point. This is done purposely to make the readers understand the difference in answers when we use concepts of string formatting.

Method 3: Directly using the math library

import math

def square_root(num):
   
    result = math.sqrt(num)
    print('The square root of %0.3f is %0.3f'%(num ,result))

num = int(input("Enter the number you want to find the square root of: "))
square_root(num)

Output:

Enter the number you want to find the square root of: 48
The square root of 48.000 is 6.928

Explanation:

Here we directly used the in-built math library. This library offers various math-related functions and out of those functions, we made use of the sqrt() function. We simply have to pass the number whose square root we want to find.

Here is the end of this article on Python programming to create a function that calculates the square root of a number. We discussed overall three methods and the most widely used is the third one as it is easy and simple.

Share:
Avatar of Dhvanil V

Author: Dhvanil V

Leave a Reply

Your email address will not be published. Required fields are marked *