Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/293.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python I';我得到一个缩进错误。我怎么修理它?_Python_Exception_Error Handling_Indentation_Code Formatting - Fatal编程技术网

Python I';我得到一个缩进错误。我怎么修理它?

Python I';我得到一个缩进错误。我怎么修理它?,python,exception,error-handling,indentation,code-formatting,Python,Exception,Error Handling,Indentation,Code Formatting,我有一个Python脚本: if True: if False: print('foo') print('bar') 但是,当我尝试运行脚本时,Python会引发一个IndentationError: File "script.py", line 4 print('bar') ^ IndentationError: unindent does not match any outer indentatio

我有一个Python脚本:

if True:
    if False:
        print('foo')
   print('bar')
但是,当我尝试运行脚本时,Python会引发一个
IndentationError

  File "script.py", line 4
    print('bar')
               ^
IndentationError: unindent does not match any outer indentation level
我一直在玩我的程序,我还能够产生四个其他错误:

  • 缩进错误:意外缩进
  • 缩进错误:应为缩进块
  • 缩进错误:未缩进与任何外部缩进级别不匹配
  • TabError:缩进中制表符和空格的使用不一致
这些错误意味着什么?我做错了什么?如何修复代码?

为什么缩进很重要? 在Python中,缩进用于定界。这与许多其他使用大括号
{}
来划分块(如Java、Javascript和C)的语言不同。因此,Python用户必须密切注意何时以及如何缩进代码,因为空格很重要

当Python遇到程序缩进问题时,它会引发一个名为或的异常

一点历史

Python使用缩进而不是公认的大括号
{}
的历史原因在-Python的创建者中概述:

Python对缩进的使用直接来自ABC,但这个想法并不是源于ABC——它已经由Donald Knuth推广,是一个众所周知的编程风格概念。(occam编程语言也使用了它。)然而,ABC的作者确实发明了冒号的用法,将引入子句与缩进块分开。在没有冒号的早期用户测试之后,人们发现,对于初学者来说,缩进的意义并不清楚,因为他们被教授了编程的第一步。添加了冒号,这一点非常清楚:冒号以某种方式吸引了人们对后面内容的注意,并以正确的方式将前后的短语联系在一起

如何缩进代码? 缩进Python代码的基本规则(考虑到您将整个程序视为“基本块”)是:基本块中的第一条语句,以及其后的每一条语句必须缩进相同的量

因此,从技术上讲,以下Python程序是正确的:

def perm(l):
        # Compute the list of all permutations of l
    if len(l) <= 1:
                  return [l]
    r = []
    for i in range(len(l)):
             s = l[:i] + l[i+1:]
             p = perm(s)
             for x in p:
              r.append(l[i:i+1] + x)
    return r
在本例中,
if
块中的
can_drive=True
行与前面任何语句的缩进不匹配:

>>> age = 10
>>> can_drive = None
>>> 
>>> if age >= 18:
...     print('You can drive')
...      can_drive = True # incorrectly indented
  File "<stdin>", line 3
    can_drive = True # incorrectly indented
    ^
IndentationError: unexpected indent
>>> if True:
... 
  File "<stdin>", line 2
    
    ^
IndentationError: expected an indented block
>>> if True:
...     if True:
...         print('yes')
...    print()
  File "<stdin>", line 4
    print()
          ^
IndentationError: unindent does not match any outer indentation level
但是,如果您确定该行确实需要缩进,则缩进需要与同一块中先前语句的缩进相匹配。在上面使用
if
的第二个示例中,我们可以通过确保带有
can\u drive=True
的行缩进到与
if
正文中前面语句相同的级别来修复错误:

>>> age = 10
>>> can_drive = None
>>> 
>>> if age >= 18:
...     print('You can drive')
...     can_drive = True # indent this line at the same level.
... 
“缩进错误:预期为缩进块”是什么意思? 问题

当Python看到复合语句的“header”时会发生此错误,例如
if:
while:
,但从未定义复合语句的主体或块。例如,在下面的代码中,我们开始了一个
if
语句,但我们从未为该语句定义主体:

>>> age = 10
>>> can_drive = None
>>> 
>>> if age >= 18:
...     print('You can drive')
...      can_drive = True # incorrectly indented
  File "<stdin>", line 3
    can_drive = True # incorrectly indented
    ^
IndentationError: unexpected indent
>>> if True:
... 
  File "<stdin>", line 2
    
    ^
IndentationError: expected an indented block
>>> if True:
...     if True:
...         print('yes')
...    print()
  File "<stdin>", line 4
    print()
          ^
IndentationError: unindent does not match any outer indentation level
评论不算作正文:

>>> if True:
...     # TODO
...
  File "<stdin>", line 3

    ^
IndentationError: expected an indented block
另一种常见情况是,出于某种原因,用户可能不想为复合语句定义实际的主体,或者主体可能被注释掉。在这种情况下,可以使用该语句。
pass
语句可以在Python希望将一个或多个语句用作占位符的任何位置使用:

pass是一个空操作-当它被执行时,什么也不会发生。当语法上需要语句,但不需要执行代码时,它可用作占位符,例如:

def f(arg): pass    # a function that does nothing (yet)

class C: pass       # a class with no methods (yet)
>>> if True:
...     if True: # tab
...         pass # tab, then 4 spaces
... 
>>>
>>> if True:
...     pass # tab
...     pass # 4 spaces
  File "<stdin>", line 3
    pass # 4 spaces
                ^
IndentationError: unindent does not match any outer indentation level
下面是上面的示例,其中使用
pass
关键字修复了
if
语句:

>>> if True:
...     pass # We don't want to define a body.
... 
>>>
“缩进错误:未缩进不匹配任何外部缩进级别”是什么意思? 问题

当取消对语句的缩进时会发生此错误,但现在该语句的缩进级别与以前任何语句的缩进级别都不匹配。例如,在下面的代码中,我们取消第二次调用
print
。但是,缩进级别与以前任何语句的缩进级别都不匹配:

>>> age = 10
>>> can_drive = None
>>> 
>>> if age >= 18:
...     print('You can drive')
...      can_drive = True # incorrectly indented
  File "<stdin>", line 3
    can_drive = True # incorrectly indented
    ^
IndentationError: unexpected indent
>>> if True:
... 
  File "<stdin>", line 2
    
    ^
IndentationError: expected an indented block
>>> if True:
...     if True:
...         print('yes')
...    print()
  File "<stdin>", line 4
    print()
          ^
IndentationError: unindent does not match any outer indentation level
我仍然收到缩进错误,但我的程序似乎缩进正确。我该怎么办? 如果您的程序看起来缩进正确,但仍然出现
IndentationError
,则很可能是混合制表符和空格。这有时会导致Python产生奇怪的错误。有关此问题的更深入解释,请参见下的特殊情况小节“TabError:缩进中制表符和空格的使用不一致”是什么意思?

“TabError:缩进中制表符和空格的使用不一致”是什么意思? 问题

此错误仅在尝试将制表符和空格混合作为缩进字符时发生。如上所述,Python将不允许您的程序混合包含制表符和空格,如果发现有异常,它将引发特定的异常
TabError
。例如,在下面的程序中,制表符和空格的组合用于缩进:

>>> if True:
...     if True:
...         print()
...     print()
...     print()
  File "<stdin>", line 5
    print()
          ^
TabError: inconsistent use of tabs and spaces in indentation
有时,Python会简单地阻塞制表符和空格的混合,并在
TabError
更合适时错误地引发
IndentationError
异常。另一个例子:

def f(arg): pass    # a function that does nothing (yet)

class C: pass       # a class with no methods (yet)
>>> if True:
...     if True: # tab
...         pass # tab, then 4 spaces
... 
>>>
>>> if True:
...     pass # tab
...     pass # 4 spaces
  File "<stdin>", line 3
    pass # 4 spaces
                ^
IndentationError: unindent does not match any outer indentation level
运行上述代码时,将引发一个
语法错误

Traceback (most recent call last):
  File "python", line 4
    else:
       ^
SyntaxError: invalid syntax
尽管Python提出了一个
SyntaxError
,但上面代码的真正问题是第二个
pass
语句应该缩进。因为第二个
pass
没有缩进,Python没有意识到前面的
if
语句和
else
语句是我的
{
    "tab_size": 4,
    "translate_tabs_to_spaces": true
}