2

I'm getting IndentationError: unexpected indent even though I wrote the code exactly as shown in the book (Learn Pythhon the hard way)

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

I am 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 are the first three lines of my code:

def sort_words(words):
    """Sorts the words"""
    return sorted(words)
1
  • I'm using Notepadd++ to compile my code, if that matters Commented Feb 9, 2013 at 11:18

2 Answers 2

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?

Sign up to request clarification or add additional context in comments.

4 Comments

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?
You can have Notepad++ fix your indentation for you: Notepad++ tabs to spaces. Did you run python -tt on your script?
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
@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.
0

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?

2 Comments

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
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.