Calculate Square Root in Python

math.sqrt. Negative input: don't call it. Python will throw, not politely refuse.

BeginnerBasic Python ProgramsExample 14 of 25
calculate-square-root.py
1# Program to calculate the square root of a number
2
3import math
4
5num = float(input("Enter a non-negative number: "))
6
7if num < 0:
8 print("Square root is not defined for negative numbers in real numbers.")
9else:
10 result = math.sqrt(num)
11 print("Square root of", num, "is", result)

Output

Enter a non-negative number: 16
Square root of 16.0 is 4.0

In this one

  • import math, then math.sqrt
  • check < 0 yourself or you get a traceback

What's going on

import math then math.sqrt(num).

math.sqrt(-1) raises ValueError. The if num < 0 is you catching that before the traceback.

16 ** 0.5 also works. math.sqrt is the readable one. Imaginary numbers are a different library and a different day.

After this program

If the idea is still fuzzy, read Day 1: Introduction to Python in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 25 basic python programs, or see every topic on Python exercises.