我的代码从文档字符串返回异常,我看不到问题:
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函数文档字符串中被注释掉,则代码可以正常工作。我希望它很简单,但我没有看到它。
谢谢!
答案 0 :(得分:4)
您混合了标签和空格,导致Python对缩进级别的哪些语句感到困惑。在Python 3上,你应该得到一个错误,特别是通知你标签和空格的混合不一致,但看起来由于某种原因没有发生。
停止混合标签和空格。打开"显示空白"在你的编辑器中使问题可见,并查看是否有"转换标签到空格"用于查找和修复标签的工具。