Google News
logo
Python Program to Return the square root of a number
In the following example of Python program to return the square root of a number using the `sqrt()` function from the `math` module :
Program :
import math

num = float(input("Enter a number: "))

if num >= 0:
    result = math.sqrt(num)
    print(f"The square root of {num} is {result:.2f}")
else:
    print("Invalid input. The number must be non-negative.")
Output :
Enter a number: 4
The square root of 4.0 is 2.00
Explanation :

1. We first import the `math` module, which provides various mathematical functions.

2. We ask the user to enter a number and convert the input to a floating-point number using the `float()` function.

3. We check if the number is non-negative. If it is, we use the `sqrt()` function from the `math` module to calculate its square root and store the result in the `result` variable. We also use string formatting to display the input number and the calculated square root with 2 decimal places.

4. If the number is negative, we print an error message.