Python - 语法错误和缩进错误

Python - SyntaxError and IndentationError

我知道 python 是一种解释器语言,这意味着它在 运行 时间解释代码,那么为什么该代码给我 IndentationError?

def function(x):
    if x:

它是否在 运行 之前检查所有代码?

因为缩进是Python语法的一个元素,所以在语法分析时会检查它。

当Python加载模块时,源代码运行通过Python解释器和"compiled"进入内部数据结构。因此,违反 Python 语法规则的错误会在加载时被捕获。

您需要在 "if x:" 语句之后添加一些内容。以下是您至少需要避免错误的内容。

    def function(x):
        if x:
            pass

在Python中,函数是对象。

您会立即收到错误消息,因为 Python 解释器由于语法不正确而无法根据您的函数定义构造函数对象。在这种情况下,您的 if 语句后没有缩进块。

https://docs.python.org/2/tutorial/controlflow.html#defining-functions

创建函数实例发生在调用函数之前。

>>> def errorOnCall(x):
...     return x / 0
... 
>>> print errorOnCall
<function errorOnCall at 0x7f249aaef578>

由于没有语法错误而创建的函数对象,但是当我们调用它时该函数会引发错误。

>>> errorOnCall(42)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in errorOnCall
ZeroDivisionError: integer division or modulo by zero

现在只要我们调用这个函数就会抛出一个错误。

>>> def errorOnDefinition(x):
...     if x:
... 
  File "<stdin>", line 3

    ^
IndentationError: expected an indented block

当我们完成定义我们的函数但在我们调用它之前抛出这个错误。解释器无法从这个无效定义创建函数实例。

我没有收到任何缩进错误

 def function(x):
   if x:
       print x

我是 python 的新手,你能解释一下你是如何得到这个错误的吗??? 当我尝试 ipython 不允许我在不输入任何 statement.so 的情况下结束行时,我在您的代码中添加了 "print x "。