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