How to Find the Square Root of a Number in Python (Without Importing Any Libraries)

Calculating the square root of a number is a great way to practice basic arithmetic and string formatting in Python. In the video below, we walk through a simple script that computes the square root using pure math without importing any external libraries.

Python Code: Square Root Calculator

You can run this code directly in any Python environment by changing the value assigned to number:

number = 4
number_sqrt = number ** 0.5
print('The square root of %0.3f is %0.3f' % (number, number_sqrt))

Sample Output

The square root of 4.000 is 2.000

How This Script Works

  • Set the Input Value: We assign the integer 4 to the variable number. You can swap this with any positive number or decimal.
  • Calculate Using the Exponent Operator (**): In mathematics, raising a number to the power of 0.5 (one-half) is identical to taking its square root. Python computes number ** 0.5 natively and stores the result in number_sqrt.
  • Format the Output: The %0.3f placeholder formats both floating-point numbers to exactly three decimal places so the output stays clean and readable.

Alternative Approach: Using Python's math.sqrt()

If you prefer using Python's built-in standard library for readability, you can also import the math module:

import math

number = 4
print(f"The square root of {number:.3f} is {math.sqrt(number):.3f}")

Note that both methods work for zero and positive numbers, while passing a negative number to math.sqrt() raises a ValueError.

Have a Python concept you would like broken down next? Drop a comment below or subscribe on YouTube (@programmer_script99) for more bite-sized coding tutorials!

Comments

Popular posts from this blog

🌐🤖 Modi Calls for Inclusive AI, Unveils MANAV Framework

Amazon CodeGuru

☁️ Cloud Services: The Hidden Playground of Cybercriminals