Exponentiation using builtins and pow

suggest change

Exponentiation can be used by using the builtin pow-function or the ** operator:

2 ** 3    # 8
pow(2, 3) # 8

For most (all in Python 2.x) arithmetic operations the result’s type will be that of the wider operand. This is not true for **; the following cases are exceptions from this rule:

2 ** -3
# Out: 0.125 (result is a float)
(-2) ** (0.5)  # also (-2.) ** (0.5)    
# Out: (8.659560562354934e-17+1.4142135623730951j) (result is complex)

The operator module contains two functions that are equivalent to the **-operator:

import operator
operator.pow(4, 2)      # 16
operator.__pow__(4, 3)  # 64

or one could directly call the __pow__ method:

val1, val2 = 4, 2
val1.__pow__(val2)      # 16
val2.__rpow__(val1)     # 16
# in-place power operation isn't supported by immutable classes like int, float, complex:
# val1.__ipow__(val2)

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents