Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Indentation of an IF-ELSE block in Python

I am Python newbie and I am working on NLP using Python. I am having an error in writing an if-else block in Python. When I am writing only an if block at that time it is working fine:

if xyzzy.endswith('l'):
    print xyzzy

After entering a colon (:) I am pressing Enter and it is automatically taking me to the correct indentation.

But when I am trying to add an else block to it after pressing the Enter key after the print statement, it is considering it to be statement of an IF block only, so it is giving me incorrect indentation as I want an else block after, while when I am trying to write else block my self it is giving me this error.

else:
   ^

IndentationError: unexpected indent

What should I do after writing print statement? Enter is clearly not working, because it is taking the cursor forward, while when I use space to come to the correct pointer it is giving me an error.

like image 783
Dude Avatar asked Dec 12 '22 22:12

Dude


2 Answers

It's hard to see from your post what the problem is, but an if-else is formatted like so

 if someCondition:
     do_something       # could be a single statement, or a series of statements
 else:
     do_something_else  # could be a single statement, or a series of statements

I.e., the else needs to be at the same level as the corresponding if.

See this Python doc/tutorial on if, and this other tutorial too.

Sometimes when your editor does autoindent for you and you edit manually too things might get messed up, so you'll have to figure out how your editor handles indentations (e.g., is it always using tabs or spaces?, what happens if you hit return etc).

Also, be wary of mixing tabs and spaces, that will cause problems too (hard to spot since both are "invisible")

With your updated post:

   if xyzzy.endswith('l'):
       print xyzzy
   else:
       something_else
like image 142
Levon Avatar answered Dec 22 '22 04:12

Levon


The else should be at the same level of indentation as the if with which it is coupled:

if x:
    # Do something
else:
    # Do something else

In your case,

if xyzzy.endswith('l'):
    print xyzzy
else:
    # Something else

Even if your editor is auto-indenting for you, you should still un-indent to make the code syntactically correct.

like image 24
arshajii Avatar answered Dec 22 '22 06:12

arshajii