如何立方数字

use*_*416 2 python syntax syntax-error exponentiation

我今天刚开始使用Python作为我的课程,我的一个问题是在Python中使用数字.我知道这样做的方法是x^3,但这在Python中不起作用.我只是想知道我将如何做到这一点.

这是我到目前为止所尝试的,但正如您所看到的,我不断收到语法错误:

>>> def volume (v) :
    return v^3
volume(4)
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)

iCo*_*dez 14

Python使用**运算符进行求幂,而不是^运算符(这是一个按位异或):

>>> 3*3*3
27
>>>
>>> 3**3  # This is the same as the above
27
>>>
Run Code Online (Sandbox Code Playgroud)

但请注意,由于之前没有换行符,因此引发了语法错误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
>>>
Run Code Online (Sandbox Code Playgroud)

当您在交互式解释器中时,换行允许Python知道函数的定义volume已完成.