Calculate Square Root in Python
Call Python math.sqrt only after checking the real-number domain. A beginner lesson connects square roots, float results, negative input, and ValueError.
1# Program to calculate the square root of a number23import math45num = float(input("Enter a non-negative number: "))67if 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)
Sample Output
Square root of 16.0 is 4.0
The root of 16.0 is returned as the float 4.0.
In this one
- Import and call math.sqrt
- Guard the real-number domain
- Distinguish a square root from a perfect-square check
How it works
- 1
Import math and convert the input with float.
- 2
Reject num < 0 before calling the library function.
- 3
Store math.sqrt(num) in result and print it.
Edge cases
Zero
Enter 0.
Zero has square root 0.0 and passes the non-negative check.
Negative input
Enter -1.
The first branch prints a message and avoids math.sqrt entirely.
What's going on
import math gives access to math.sqrt. A square root is a number that produces the original value when multiplied by itself. For 16, the non-negative square root is 4.
The code checks num < 0 before calling sqrt. math.sqrt(-1) raises ValueError because this function works with real numbers, not complex results. The validation branch prints an explanation instead of reaching that error.
The sample converts 16 to 16.0, and sqrt returns 4.0. A value need not be a perfect square: sqrt(2) is an approximate float. num ** 0.5 can express a similar calculation for non-negative values, but math.sqrt states the intention plainly. Blank input still raises ValueError during float conversion; the negative check is not a general input-error handler.
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.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Why check for a negative number?
Pick an answer to check it.
Question 2
Must the input be a perfect square?
Pick an answer to check it.
Questions people ask
Why check for a negative number?
math.sqrt raises ValueError for negative real inputs, so the check avoids that call.
Must the input be a perfect square?
No. math.sqrt can return an approximate float such as the square root of 2.
Why is the result printed as 4.0?
math.sqrt returns a float even when the mathematical root is an integer.