Search code examples
pythonindentationcpython

Possible mixed indentation in Python?


Looking at this question, I tried OP's the code on my machine. Here are a text version and a screenshot:

bad square

What just happened? This supposed to be a square function, and it is implemented correctly. To be sure, I copy-pasted the code, and tried it again:

good square

Well, I can't see any difference between these versions of square, but only the latter works.

The only reason I can think of is that I may have mixed tabs and spaces, so the return statement is actually indented, and so the loop is executed exactly once. But I could not reproduce it, and it looks like an unbelievable flaw in the interpreter's mixed-indentation-check. So I have two questions, or maybe three:

  1. What do I miss?
  2. If this is a mixed indentation thing, what it may be, exactly?
  3. If this is a mixed indentation thing, why wasn't it caught by the interpreter? Obviously the whole idea of indentation in python (and in general) is to avoid such problems. And it's too important to let such things slip.

Solution

  • Easy!

    def square(x):
        runningtotal = 0
        for counter in range(x):
            runningtotal = runningtotal + x
    <tab>return runningtotal
    

    First, tabs are replaced (from left to right) by one to eight spaces such that the total number of characters up to and including the replacement is a multiple of eight <...>

    So this tab on the last line is replaced with 8 spaces and it gets into the loop.