Python Square Root
Square root, also called the second root, is represented as [√ ̄]. For example, in mathematical language: √ ̄16=4. In verbal description: the square root of 16 is 4.
The following example takes a number input from the user and calculates the square root of that number:
Example (Python 3.0+)
# -*- coding: UTF-8 -*-
# Filename : test.py
# author by : www.example.com
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))
Executing the above code produces the following output:
$ python test.py 请输入一个数字: 4 4.000 的平方根为 2.000
In this example, we take a number input from the user and use the exponent operator ** to calculate the square root of that number.
This program is only suitable for positive numbers. Negative numbers and complex numbers can use the following method:
Example (Python 3.0+)
# -*- coding: UTF-8 -*-
# Filename : test.py
# author by : www.example.com
# Calculate the square root of real and complex numbers
# Import the complex math module
import cmath
num = int(input("Please enter a number:"))
num_sqrt = cmath.sqrt(num)
print('The square root of {0} is {1:0.3f}+{2:0.3f}j'.format(num ,num_sqrt.real,num_sqrt.imag))
Executing the above code produces the following output:
$ python test.py 请输入一个数字: -8 -8 的平方根为 0.000+2.828j
In this example, we used the sqrt() method of the cmath (complex math) module.
Other Extensions
Python3 Examples