2016-08-14 48 views
0

我的代碼返回從文檔字符串的例外,我看不出問題:簡單的Python文檔例外

def printBreak(title): 
    """Prints a dotted line""" 
    print("------" + title + "------") 

def printWords(theWords): 
    """Prints the passed array with word length and word""" 
    for w in theWords: 
     print(len(w), w) 
    print("") 

def sortWordsByLength(theWords): 
    """Word array sorted by length""" 
    for w in theWords: 
     for i in range(len(wordsSortedByLength)): 
      if len(w) > len(wordsSortedByLength[i]): 
       wordsSortedByLength.insert(i,w) 
       break 
     else: 
      wordsSortedByLength.append(w) 


def main(): 
    printBreak("Initial word array") 
    printWords(words) 
    printBreak(sortWordsByLength.__doc__) 
    sortWordsByLength(words[1:]) 
    printWords(wordsSortedByLength) 

# Sort some strings 
words = ['happy', 'cat', 'window', 'appetite', 'gophery', 'it', 'perky'] 
wordsSortedByLength = [words[0]] 
main() 

錯誤:

File "/Users/bevilacm/source/Python/Scripts/sortWords.py", line 7 
for w in theWords: 
       ^
IndentationError: unindent does not match any outer indentation level 
[Finished in 0.1s with exit code 1] 

如果文檔字符串被註釋掉printWords函數文檔字符串,代碼有效。我期望它是簡單的東西,但我沒有看到它。

謝謝!

回答

4

您混合了製表符和空格,導致Python對什麼語句處於縮進級別感到困惑。在Python 3中,你應該得到一個特別通知你標籤和空格混合不一致的錯誤,但是看起來這不是由於某種原因而發生的。

停止混合標籤和空格。打開編輯器中的「顯示空白」以使問題可見,並查看是否存在「將製表符轉換爲空格」工具來查找和修復製表符。