askvity

How to Find Square Root in Python?

Published in Math Operations 2 mins read

To find the square root of a number in Python, you need to utilize the math module.

Using the math.sqrt() Function

The math module provides a function called sqrt() specifically for calculating square roots. Here's how to use it:

  1. Import the math module: You must first import the math module into your Python script using the command import math. This makes all the functions in the math module available for use.

  2. Use the math.sqrt() function: After importing the module, you can calculate the square root of a number by passing that number as an argument to the math.sqrt() function.

Example

import math

number = 25
square_root = math.sqrt(number)
print(f"The square root of {number} is: {square_root}") # Output: The square root of 25 is: 5.0

number = 2
square_root = math.sqrt(number)
print(f"The square root of {number} is: {square_root}") # Output: The square root of 2 is: 1.4142135623730951

Practical Insights

  • Data Type: The math.sqrt() function will always return a float value, even if the square root is a whole number.

  • Error Handling: The math.sqrt() function will raise a ValueError if given a negative number, because the square root of a negative number is not a real number. You can use a try-except block to handle such cases.

    import math
    
    try:
      number = -25
      square_root = math.sqrt(number)
      print(f"The square root of {number} is: {square_root}")
    except ValueError as e:
      print(f"Error: {e}") # Output: Error: math domain error
  • Other Libraries: While math.sqrt() is the most direct way, other libraries like numpy also offer similar functions, which are useful for handling arrays or more complex calculations. For instance, numpy.sqrt() can operate on multiple numbers at once.

Key takeaway: To find the square root in Python, import the math module, and use the math.sqrt() function. This function takes a number as input and returns its square root as a floating-point value.

Related Articles