Python math.sqrt() function


The math.sqrt() function in Python is used to calculate the square root of a non-negative number. It is part of the math module, which provides various mathematical functions and constants.

Syntax

import math result = math.sqrt(x)
  • x: The number for which you want to find the square root. It must be a non-negative number (either an integer or a float).

Return Value

  • Returns the square root of x. If x is negative, a ValueError is raised.

Examples

  1. Calculating the square root of a positive integer:

    import math result = math.sqrt(16) print(result) # Output: 4.0
  2. Calculating the square root of a positive float:

    result = math.sqrt(20.25) print(result) # Output: 4.5
  3. Using math.sqrt() with zero: The square root of zero is zero.

    result = math.sqrt(0) print(result) # Output: 0.0
  4. Handling negative numbers: If you try to compute the square root of a negative number, a ValueError is raised:

    try: result = math.sqrt(-4) except ValueError as e: print(e) # Output: math domain error
  5. Using the square root in mathematical expressions: You can use math.sqrt() in larger expressions:

    # Calculate the hypotenuse of a right triangle using the Pythagorean theorem a = 3 b = 4 hypotenuse = math.sqrt(a**2 + b**2) print(hypotenuse) # Output: 5.0

Summary

  • The math.sqrt() function computes the square root of a non-negative number.
  • It returns a float, and attempting to compute the square root of a negative number raises a ValueError.
  • It is a simple and efficient way to perform square root calculations in Python.