0
0
PythonProgramBeginner · 2 min read

Python Program to Find Square Root of a Number

You can find the square root of a number in Python using import math and then math.sqrt(number) to get the result.
📋

Examples

Input16
Output4.0
Input25
Output5.0
Input0
Output0.0
🧠

How to Think About It

To find the square root of a number, think about what number multiplied by itself gives the original number. We use the math.sqrt() function in Python which does this calculation for us easily.
📐

Algorithm

1
Get the number input from the user.
2
Import the math module to access the square root function.
3
Use math.sqrt() with the input number to calculate the square root.
4
Print the result.
💻

Code

python
import math

number = float(input("Enter a number: "))
sqrt_value = math.sqrt(number)
print("Square root of", number, "is", sqrt_value)
Output
Enter a number: 16 Square root of 16.0 is 4.0
🔍

Dry Run

Let's trace the input 16 through the code

1

Input number

User enters 16, stored as number = 16.0

2

Calculate square root

math.sqrt(16.0) returns 4.0

3

Print result

Output: Square root of 16.0 is 4.0

StepVariableValue
1number16.0
2sqrt_value4.0
3print outputSquare root of 16.0 is 4.0
💡

Why This Works

Step 1: Import math module

We import math to use its built-in square root function.

Step 2: Get user input

We convert the input to float to handle decimal numbers.

Step 3: Calculate square root

Using math.sqrt() returns the positive square root of the number.

Step 4: Display result

We print the original number and its square root for clarity.

🔄

Alternative Approaches

Using exponentiation operator
python
number = float(input("Enter a number: "))
sqrt_value = number ** 0.5
print("Square root of", number, "is", sqrt_value)
This method uses the power operator and is simple but less explicit than math.sqrt.
Using pow() function
python
number = float(input("Enter a number: "))
sqrt_value = pow(number, 0.5)
print("Square root of", number, "is", sqrt_value)
The built-in pow() function can also calculate roots by raising to 0.5 power.

Complexity: O(1) time, O(1) space

Time Complexity

Calculating square root using math.sqrt or exponentiation is a constant time operation.

Space Complexity

Only a few variables are used, so space complexity is constant.

Which Approach is Fastest?

Using math.sqrt is optimized and clear, exponentiation is simple but slightly less explicit.

ApproachTimeSpaceBest For
math.sqrt()O(1)O(1)Clear and standard method
Exponentiation operator (** 0.5)O(1)O(1)Simple and concise
pow() functionO(1)O(1)Built-in alternative to exponentiation
💡
Always convert input to float to handle decimal numbers when finding square roots.
⚠️
Trying to find square root of a negative number without handling errors causes a ValueError.