33
votes
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?

3
Side note: ** is exponential, but doing multiplication when you know the exponent (i.e. x*x and y*y*y instead of x**2 and x**3) is faster. - Matthew

3 Answers

84
votes

^ is the xor operator.

** is exponentiation.

2**3 = 8

14
votes

You can also use the math library. For example:

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

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]))