-2

When I hit enter after typing else: to move to the next line, it gives error indentation, no matter how I align it, i tried 4 spaces, everything still not working. I made sure that else is aligned perfectly with if as in the book, but still error.

Can someone please explain to me how indentation works? I'm using Python 2.7

Code:

if x%2 == 0:
    print "Even"
else: 
    print "Odd"
print "done with conditional"

screenshot of console session

melpomene
  • 84,125
  • 8
  • 85
  • 148
Jacksoja
  • 1
  • 1
  • 3

2 Answers2

1

Assume as if python has an reverse hierarchical structure like an inverted traingle.

  1. when ever you want to write function/loop/conditions in 1st level, we write whatever the code we are writing inside those three sections in 2nd level.

  2. In your code "if" and "else" comes in 1st level. so dont give any spaces infront of these.

  3. print statements inside 'if' and 'else' should have same tab space or white space as they come under 2nd level.

  4. outer print statement will not have a space because it again comes to 1st level.

Hope this helps

-1

In Python console, everything works fine with a positive number of spaces, or a Tab; so any of these example will work:

if True:
 print('Hello')
else:
 print('Not hello')

if True:
    print('Hello')
else:
    print('Not hello')

if True:
        print('Hello')
else:
        print('Not hello')

EDIT For searching where is the problem, try this answer; call

python -m tabnanny <your_script>.py

and you will get an output telling you which lines are the problem.

Example output:

'test.py': Indentation Error: unindent does not match any outer indentation level (<tokenize>, line 12)
crissal
  • 2,547
  • 7
  • 25
  • thank you , but in my example. if x%2 == 0: print "Even" else: ( here when I hit enter in my keyboard, it gives error message, i cannot move to the next line ) – Jacksoja Jun 20 '19 at 09:17
  • 1
    How does this solve the op's problem? they've already included an example with correct indentation – Sayse Jun 20 '19 at 09:18
  • @Sayse I answered before op updated with the problem he got (and then edited) – crissal Jun 20 '19 at 09:20
  • 1
    @crissal - The op's [initial post](https://stackoverflow.com/revisions/5054b20e-4af9-40b5-b07a-025ad690cbc4/view-source) contained the correct indentation. – Sayse Jun 20 '19 at 09:21
  • I talk about the comment – crissal Jun 20 '19 at 09:22
  • btw @Jacksoja try putting these lines into a file and run tabnanny – crissal Jun 20 '19 at 09:23