Python Tutorial (33) - Example: Square Root

Time: Column:Python views:220

Calculating Square Roots

The square root, also known as the second root, is denoted as sqrt{} For example, in mathematical notation: 16=4sqrt{16} = 4.In descriptive language: "The square root of 16 is 4."

The following example demonstrates how to calculate the square root of a number provided by the user:

Example (Python 3.0+):

# -*- coding: UTF-8 -*-

num = float(input('Please enter a number: '))
num_sqrt = num ** 0.5
print('The square root of %0.3f is %0.3f' % (num, num_sqrt))

When executing the above code, the output will be:

Output:

$ python test.py
Please enter a number: 4
The square root of 4.000 is 2.000

In this example, the program calculates the square root of a number input by the user using the exponentiation operator ** with 0.5.

This program is suitable for positive numbers only. For negative numbers and complex numbers, use the following approach:

Example (Python 3.0+):

# -*- coding: UTF-8 -*-

# Calculate square roots for real and complex numbers
# Import the complex math module
import cmath

num = int(input("Please enter a number: "))
num_sqrt = cmath.sqrt(num)
print('{0} has a square root of {1:0.3f}+{2:0.3f}j'.format(num, num_sqrt.real, num_sqrt.imag))

When executing this code, the output will be:

Output:

$ python test.py
Please enter a number: -8
-8 has a square root of 0.000+2.828j

In this example, we use the sqrt() method from the cmath (complex math) module to handle both real and complex square roots.