Lesson 2 and Lesson 3 Indentation Discrepancy



Here is my correct code from lesson 2:

def is_even(x):
  for i in x:
    if i % 2 == 0:
        print i, "is even"
        print i, "is odd"
numbers = [25, 60, 85, 143]

Here is my correct code from lesson 3:

def is_int(x):
  if float(x) - int(x) == 0:
    print x, "is an integer"
    return True
    print x, "is not an integer"
    return False

In lesson 2, when I indent my print statement 4 spaces, it works. If I only do two spaces, it gives me an indentation error.

In lesson 3, it’s the opposite. When I indent 2 spaces, my print statement works. If I try to indent 4 spaces, I get an indentation error.

Can anyone explain this? I feel like I am not understanding the indentation rules in python. I don’t understand why these two function are so different.


The explanation is that you missed something. 2 or 4 are both fine as far as python is concerned. The python community in general has agreed on 4 spaces.

Most likely, you changed indentation in one place but it needed to be the same at some other place in order to make sense.

 print('b')  # doesn't match indentation level

Python is fine with tabs too, but you absolutely must not mix them (because that’s really confusing, looks different in different editors) (but again, 4 spaces is preferred)

Indentation shouldn’t give you much trouble. Indent for loop/function/class etc body (after their colons), and then go back out again to exit.

Feel free to post what you think should be ok, but isn’t.


Right, but you can see my code, so what did I miss? I’m not following. Thanks!


You said you posted correct code though. So no, I can’t see the code you’re asking about.


Right, I’m saying that in the code that I posted (the correct code), everything works fine in both, but I don’t understand why the indentation is 4 spaces in one and 2 in the other.


Because you wrote it that way. If you mean that it needs to be that way, no. It doesn’t.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.