[Tutor] How do I do square roots and exponents?

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Wed, 27 Mar 2002 17:26:50 -0800 (PST)

> While toying around in Python, I decided to make a program that
> calculates the hypotenuse. I ran into a problem when I realized that I
> had no idea what the command was for square roots and exponents. Does
> anyone know?

Hi James,

Python has an exponentiation operator using the double stars "**", so you
can do something like this:

>>> 2 ** (0.5)
>>> 2 ** 8

If you'd rather like to use functions to do this, you may also find the
functions in the 'math' module very useful:


>>> math.sqrt(2)
>>> math.pow(2, 8)

(Notice that math.pow is defined to return a floating point value.)

Finally, if you know about complex numbers, then you'll definitely want to
look at the cmath module:


since it properly supports things like taking the square root of negative

>>> (-1) ** (0.5)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ValueError: negative number cannot be raised to a fractional power
>>> import cmath
>>> cmath.sqrt(-1)

Good luck!