How to take the square root of a number in Python
Using the Sqrt() function from the math module
-
Import the math module using import math at the beginning of the program
-
Find out the square root of the number using
math.sqrt(number)method -
Note that it throws an error if a negative number is passed
import mathprint(math.sqrt(19))# Throws an error if a negative number is passed#print(math.sqrt(-19))
Writing a function
-
Create a function that takes one argument
-
Then, if the number is negative, return nothing. (Imaginary numbers are another topic for another shot)
-
Now, as a square root of a number is simply the number raised to the power 0.5, raise the given number to the power of 0.5 using the following syntax:
number**exponent
-
This will give us the square root of the number; return it
-
Finally, print out the result to the user
def sqrt(n):if n < 0:returnelse:return n**0.5print(sqrt(19))
Free Resources
Copyright ©2025 Educative, Inc. All rights reserved