Hi I am python newbie and I am working on NLP using python. I am having a error in writing if-else block in python. When I am writing only if block at that time it is working fine:
if xyzzy.endswith('l'):
print xyzzy
after entering colon I am pressing enter and it is automatically taking me to the correct indentation.
but when I am trying to add else block to it after pressing "Enter" key after print statement,
it is considering it to be statement of IF block only so it is giving me incorrect indentation as I want to else block after, while when I am trying to write else block my self it is giving me this error.
else:
^
IndentationError: unexpected indent
so 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 a error.
解决方案
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.
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