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!")
但是大多数编辑器允许您设置选项卡应该有多少个空格。它设置为四个,你会得到这样的:
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!")
当然,解决所有的问题是写在意见,从不使用标签。我不确定为什么Python 3仍然允许标签,真的没有什么好的理由。
在编辑器中使用_show whitespace_。 –
删除**全部**选项卡。使用4个空格 – JBernardo
谢谢,解决了我的问题。添加您的评论作为答案,所以我upvote和接受! :) – Shubham