Lesson 2 and Lesson 3 Indentation Discrepancy


#1

https://www.codecademy.com/courses/learn-python/lessons/practice-makes-perfect/exercises/isint?action=lesson_resume&link_content_target=interstitial_undefined

Here is my correct code from lesson 2:

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

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
  else:
    print x, "is not an integer"
    return False
 
is_int(7.5)

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.


#2

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('a')
 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.


#3

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


#4

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


#5

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.


#6

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


#7

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