2

I'm getting IndentationError: unexpected indent even though I wrote the code exactly as shown in the book (http://learnpythonthehardway.org/book/ex25.html)

I'm sure that I'm using exactly 4 spaces to indent the lines which come after "def".

Using Python 2.7 on Windows 7

Here's the error I get in powershell:

PS C:\Users\Kiedis\python> python ex25.py
  File "ex25.py", line 3
    return sorted(words)
    ^
IndentationError: unexpected indent

and here's the first 3 lines of my code:

def sort_words(words):
    """Sorts the words"""
    return sorted(words)
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
kamokoba
  • 497
  • 9
  • 17

2 Answers2

3

You are mixing tabs and spaces anyway; run your script with:

python -tt ex25.py

to detect where the error lies.

Then configure your editor to only use spaces for indentation, and re-indent your file. See How does one configure Notepad++ to use spaces instead of tabs?

Community
  • 1
  • 1
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • thank you Martijn. I configured Notepad++ to replace Tab by Space. I'm still getting the same error but i suppose i need to restart Notepad++ and rewrite the whole code manually? – kamokoba Feb 09 '13 at 11:39
  • You can have Notepad++ fix your indentation for you: [Notepad++ tabs to spaces](http://stackoverflow.com/q/455037). Did you run `python -tt` on your script? – Martijn Pieters Feb 09 '13 at 11:41
  • yes, I ran python -tt ex25.py and got the following: PS C:\Users\Kiedis\python> python -tt ex25.py File "ex25.py", line 7 word = words.pop(0) ^ TabError: inconsistent use of tabs and spaces in indentation – kamokoba Feb 09 '13 at 11:46
  • @ThomasH.: Then line 7 has mixed tabs and spaces. Run the `Leading tabs to spaces` TextFX on your file, and see if you need to adjust indentations and safe your file. Then run your code again. – Martijn Pieters Feb 09 '13 at 12:06
1

Make sure the comment ("""Sorts the words""") is not directly bellow the def sort_words(words). This raises an error. Did this solve your problem?

Traple
  • 21
  • 1
  • 4
  • no, it's not directly below def... The first double-quote is 4 spaces from the left. And "return" is 4 spaces from the left – kamokoba Feb 09 '13 at 11:17
  • Did you make sure you gave arguments when calling the function? Like sort_words("Words") You already said you used spaces instead of tabs so that can't be the problem. – Traple Feb 09 '13 at 11:24