Python program to find the square root of a number

Python 3 program to find the square root of a number :

To find the square root of a number in python, we have two different approaches. In this example, we will learn both of these processes one by one. We are using python 3 for this example.

Required knowledge for this example :

1. if-else in python.
2. Basics of user input.

Approaches :

We can find out the square root of a number using :

1. Simple mathematics or without using any inbuilt function.
2. Using math module.

Python3 Program to find square root without using the inbuilt function :

#1
number = int(input("Enter a number to find the square root : "))

#2
if number < 0 :
	print("Please enter a valid number.")
else :
	#3
	sq_root = number ** 0.5
	#4
	print("Square root of {} is {} ".format(number,sq_root))

Example Output :

Enter a number to find the square root : 16
Square root of 16 is 4.0

Enter a number to find the square root : 12
Square root of 12 is 3.4641016151377544

Enter a number to find the square root : -12
Please enter a valid number.

Explanation :

The commented numbers in the above program denote the step number below :

1. First, take the input number from the user and save it in variable number
2. Check if the number is a negative number. We are calculating square root only for positive numbers. If it is negative, prompt the user to enter a valid number.
3. Now, to find the square root of the number we are finding the number raised to the power 0.5. It will provide us square root of the number. Save this value in variable sq_root.
4. Finally, print out the result to the user.

Python program to find the square root of a number using math module :

import math

number = int(input("Enter a number to find square root : "))

if number < 0 :
	print("Please enter a valid number .")
else :
	print("Square root of {} is {} ".format(number,math.sqrt(number)))

Sample Output :

Enter a number to find the square root : 16
Square root of 16 is 4.0

Enter a number to find the square root : 12
Square root of 12 is 3.4641016151377544

Enter a number to find the square root : -12
Please enter a valid number.

Explanation :

The output of this process is same as the above one. The only thing we are changing is :

1. Import the math module using import math at the beginning of the program.
2. Finding out the square root of the number using math.sqrt(number) method.

You can use any of the following methods to find the square root. But always remember to check if it is a positive number or not. Else, it will throw an exception.

Leave a Reply