36
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?

Rohan Sobha
  • 395
  • 1
  • 3
  • 6
  • 2
    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 May 10 '15 at 07:33

3 Answers3

91

^ is the xor operator.

** is exponentiation.

2**3 = 8

Stefan Kendall
  • 66,414
  • 68
  • 253
  • 406
  • 7
    There is also the builtin [pow](https://docs.python.org/3/library/functions.html#pow) and [math.pow](https://docs.python.org/3/library/math.html#math.pow). – Teepeemm May 10 '15 at 20:58
  • Can you explain how it works when there are fractions like `2 ** 4.5`? – Krishnadas PC May 01 '21 at 13:08
  • @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). – ShadowRanger Oct 12 '21 at 12:58
14

You can also use the math library. For example:

import math
x = math.pow(2,3) # x = 2 to the power of 3
Dave Schweisguth
  • 36,475
  • 10
  • 98
  • 121
Iron Fist
  • 10,739
  • 2
  • 18
  • 34
2

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]))
Jommy
  • 1,020
  • 1
  • 7
  • 14
AvidLearner
  • 4,123
  • 5
  • 35
  • 48