How to cube a number

user3795416 picture user3795416 · Jul 1, 2014 · Viewed 79.6k times · Source

I just started using Python today for my class and one of my problems is cubing a number in Python. I know the way to do it is x^3, but that doesn't work in Python. I was just wondering how I would be able to do that.

This is what I tried so far, but as you can see, I keep getting syntax errors:

>>> def volume (v) :
    return v^3
volume(4)
SyntaxError: invalid syntax

Answer

user2555451 picture user2555451 · Jul 1, 2014

Python uses the ** operator for exponentiation, not the ^ operator (which is a bitwise XOR):

>>> 3*3*3
27
>>>
>>> 3**3  # This is the same as the above
27
>>>

Note however that the syntax error is being raised because there is no newline before volume(4):

>>> def volume(v):
...     return v**3
... volume(4)
  File "<stdin>", line 3
    volume(4)
         ^
SyntaxError: invalid syntax
>>>
>>> def volume(v):
...     return v**3
...                  # Newline
>>> volume(4)
64
>>>

When you are in the interactive interpreter, the newline lets Python know that the definition of function volume is finished.