Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected Indent error in Python [duplicate]

Tags:

python

I have a simple piece of code that I'm not understanding where my error is coming from. The parser is barking at me with an Unexpected Indent on line 5 (the if statement). Does anyone see the problem here? I don't.

def gen_fibs():
    a, b = 0, 1
    while True:
        a, b = b, a + b
        if len(str(a)) == 1000:
            return a
like image 776
tjsimmons Avatar asked Nov 24 '10 04:11

tjsimmons


People also ask

How do I fix an unexpected indent in Python?

“IndentationError: unexpected indent” is raised when you indent a line of code too many times. To solve this error, make sure all of your code uses consistent indentation and that there are no unnecessary indents.

What is the meaning of unexpected indent error in Python?

Errors due to indentation in Python: You may encounter the following Indentation errors: 1. Unexpected indent - This line of code has more spaces at the beginning than the one before it, but the one before it does not begin a sub block. In a block, all lines of code must begin with the same string of whitespace. 2.


2 Answers

If you just copy+pasted your code, then you used a tab on the line with the if statement. Python interprets a tab as 8 spaces and not 4. Don't ever use tabs with python1 :)

1 Or at least don't ever use tabs and spaces mixed. It's highly advisable to use 4 spaces for consistency with the rest of the python universe.

like image 90
aaronasterling Avatar answered Sep 25 '22 13:09

aaronasterling


You're mixing tabs and spaces. Tabs are always considered the same as 8 spaces for the purposes of indenting. Run the script with python -tt to verify.

like image 34
Ignacio Vazquez-Abrams Avatar answered Sep 24 '22 13:09

Ignacio Vazquez-Abrams