Reputation: 25
I am running an insertion sort algorithm, and it seems to have a fault in it. So I tried adding print statements to follow along, however when I include the print statements I get indent errors. Can someone explain why the first code does not cause a problem but the second code does?
Runs Fine:
def isort(self):
for i in range(1, len(self.array)):
temp = self.array[i]
k = i
while k > 0 and temp < self.array[k-1]:
# print self.array[k-1]
self.array[k] = self.array[k-1]
# print "k > 0 and temp < self.array[k-1]"
# print "k: " + k
# print "temp: " +temp
# print "self.array[k-1]: " + self.array[k-1]
k = k-1
self.array[k] = temp
return self.array
Errors located on lines with "#*"
def isort(self):
for i in range(1, len(self.array)):
temp = self.array[i]
k = i
while k > 0 and temp < self.array[k-1]: #* indent expected
print self.array[k-1] #* unexpected indent
self.array[k] = self.array[k-1]
# print "k > 0 and temp < self.array[k-1]" #* unindent does not match any outer indention level
print "k: " + k
# print "temp: " +temp
# print "self.array[k-1]: " + self.array[k-1]
k = k-1 #* unexpected indent
self.array[k] = temp
return self.array #* return outside of function
Upvotes: 1
Views: 1849
Reputation: 82899
You are mixing tabs and spaces for indentation.
In fact, even your first example (the one that works) has mixed tabs and spaces, but in this case they are somewhat consistent: The while
is indented with two tabs, and all the non-comment lines after that with two tabs plus some spaces.
In the second example, the while
is indented with two tabs, but the print
line after that is indented with all spaces. Thus python can not work out what block this line should belong to.
In Python 2 you can use the -t
option to check this; Python3 seems to check automatically.
>>> python2.6 -t test.py
test.py: inconsistent use of tabs and spaces in indentation
To fix it, you can do a search-and-replace to replace all tabs with groups 4 spaces or the other way around. The official way is four spaces, but there is some debate on this. Whatever, never mix!
Upvotes: 3