Python square root Code Example

Last Updated On Thursday 20th Jan 2022
  • A square root of a number is a value that gives the original number when multiplied by itself.
  • For example, 2 x 2 = 4, so a square root of 4 is 2. -2 x -2 = 4.

square root in python

  • Create a function that takes one argument as the input from the user.
  • Then, if the number is negative, it returns nothing.
  • As a square root of a number is simply the number raised to the power.
  • This will give us the square root of the number and print out the result to the user

Example 1 : Using Exponent

	n = int(input("Input : "))

def sqrt(n):
  if n < 0:
    return
  else:
    return n**0.5

print("The square root of", n, "is", sqrt(n))
	
	# Input : 25
# The square root of 25 is 5.0
	

Example 2 : Using Math.sqrt()

  • The sqrt() method returns the square root of the number x.
  • Math.sqrt() cannot be accessed directly. You need to import the math module.
	import math

import math
print(math.sqrt(100))
print(math.sqrt(36))
print(math.sqrt(math.pi))
	
	# 10.0
# 6.0
# 1.7724538509055159
	

Example 3

	n = int(input("Input : "))

def sqrt(n):
    # number entered stored as x, x is a variable carrying entered number
    x = n
    # y store x + 1 divided by 2 based on 
    y = (x + 1) / 2
    while y < x:
        x = y
        y = (x + n / x) / 2
    return y;
print("Square root of", n,sqrt(n))
	
	# Input : 49
# Square root of 49 is 7.0