Python 2 允许您混合使用空格和制表符。所以你可以有像这样的缩进:
def foo():
[this is a tab it counts like eight spaces ]for each in range(5):
[this is a tab it counts like eight spaces ][space][space]print(each)
[space][space][space][space][space][space][space][space]print("Done!")
第 2 行和第 4 行在 Python 2 中将具有相同的缩进级别,但第 2 行将使用制表符进行,而第 4 行将使用空格进行。打印到控制台,它看起来像这样:
def foo()
for each in range(5):
print(5)
print("Done!")
但大多数编辑器都允许您设置制表符应该有多少个空格。将其设置为 4,您将得到:
def foo()
for each in range(5):
print(5)
print("Done!")
缩进还是一样,但是现在看起来缩进错了!
因此,Python 3 不允许相同的缩进级别(即第 2 行和第 4 行)以不同的方式缩进。您仍然可以混合使用制表符和空格,但不能使用相同的缩进级别。这意味着
def foo():
[this is a tab it counts like eight spaces ]for each in range(5):
[this is a tab it counts like eight spaces ][space][space]print(each)
[this is a tab it counts like eight spaces ]print("Done!")
会工作,所以会
def foo():
[this is a tab it counts like eight spaces ]for each in range(5):
[space][space][space][space][space][space][space][space][space][space]print(each)
[this is a tab it counts like eight spaces ]print("Done!")
使缩进看起来怪异的唯一方法是将制表符设置为更多超过八个空格,然后缩进不仅看起来明显不正确,而且'会注意到一个制表符将缩进 12 个空格(在下面的示例中),因此您意识到您插入的是一个制表符,而不是四个空格。
def foo():
for each in range(5):
print(each)
print("Done!")
当然,所有问题的解决方案都写在 cmets 中,永远不要使用制表符。我不确定为什么 Python 3 仍然允许选项卡,真的没有很好的理由。