Python Square Root
The square root, also called the quadratic root, is written with the radical sign; in mathematical notation, the square root of 16 is 4. In words: the square root of 16 equals 4.
The following example takes a number from user input and calculates its square root:
Example (Python 3.0+)
-- coding: UTF-8 --
Filename : test.py
author by : www.runoob.com
num
=
float
(
input
(
'
Please enter a number:
'
)
)
num_sqrt
=
num
**
0.5
(
'
The square root of %0.3f is %0.3f
'
%
(
num
,
num_sqrt
)
)
The output of the code above is:
$ python test.py
请输入一个数字: 4
4.000 的平方根为 2.000
In this example we take a number from user input and use the exponentiation operator ** to calculate its square root.
This program only works for positive numbers. For negative and complex numbers, use the following approach:
Example (Python 3.0+)
-- coding: UTF-8 --
Filename : test.py
author by : www.runoob.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
)
(
'
The square root of {0} is {1:0.3f}+{2:0.3f}j
'
.
format
(
num
,
num_sqrt
.
real
,
num_sqrt
.
imag
)
)
The output of the code above is:
$ python test.py
请输入一个数字: -8
-8 的平方根为 0.000+2.828j
In this example we used the sqrt() method of the cmath (complex math) module.
Python3 Examples