How do I do exponentiation in python?

86,488

Solution 1

^ is the xor operator.

** is exponentiation.

2**3 = 8

Solution 2

You can also use the math library. For example:

import math
x = math.pow(2,3) # x = 2 to the power of 3

Solution 3

if you want to repeat it multiple times - you should consider using numpy:

import numpy as np

def cube(number):
    # can be also called with a list
    return np.power(number, 3)

print(cube(2))
print(cube([2, 8]))
Share:
86,488
Admin
Author by

Admin

Updated on October 27, 2020

Comments

  • Admin
    Admin over 3 years
    def cube(number):
      return number^3
    print cube(2)
    

    I would expect cube(2) = 8, but instead I'm getting cube(2) = 1

    What am I doing wrong?

  • Teepeemm
    Teepeemm almost 9 years
    There is also the builtin pow and math.pow.
  • Jeru Luke
    Jeru Luke almost 6 years
    the essence of being numpythonic
  • Krishnadas PC
    Krishnadas PC almost 3 years
    Can you explain how it works when there are fractions like 2 ** 4.5?
  • ShadowRanger
    ShadowRanger over 2 years
    @Teepeemm: Mind you, math.pow is basically 100% useless; ** does the job without an import, and doesn't force conversion to float. And the built-in pow is the only one accepting three arguments to efficiently perform modular exponentiation. I can't think of a single time I've ever wanted to perform exponentiation that implicitly converted my integer inputs to floating point (the only time math.pow is even remotely useful, and float(x) ** y would achieve that anyway).