简体   繁体   中英

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.

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

Ie, 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 (eg, 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

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.

Getting the indentation correct isn't really a Python issue but rather an issue with the editor that you're using for your source code.

Most editors that understand Python will correctly add one level of indentation after a colon (as you're seeing). Because you can have as many statements as you want in that block of code, the editor has no way to know when to "outdent" the next line for the else .

You have to tell the editor to outdent that line by hitting backspace or Shift + Tab on the line before starting to type.

If you are inserting the else part after the rest of the code is written, make absolutely certain that the characters you use to indent are the same as for the if statement. If the if statement is indented with spaces, use the same number of spaces for else . If the if statement is indented with one or more tabs, use the same number of tabs for the else statement. Don't mix spaces and tabs for indentation.

Don't assume that just because the lines "look" as if they're indented the same that they are indented the same. One may use spaces and one may use tabs (or some combination).

when I use space to come to the correct pointer it is giving me a error

Of course. Using space never makes a "line break", typically this is \\n in Unix systems. If you'd open your .py file in a different editor (say Notepad in Windows) you'd see that your else statement is in the same line as print.

Enter is clearly not working because it is taking the cursor forward

Press backspace the correct amount of times to reach the same level of indentation as your IF statement.

I don't agree entirely with the accepted answer. Yes, indention is very important in Python, but to state that the if-else has to always look like that with this formatting is a little bit overboard.

Python allows you a one-liners (even multiple) as long as you don't do anything fancy in there that requires indention in the body of the if , elif or else .

Here are some examples:

choice = 1
# if with one-liner
if choice == 1: print('This is choice 1')

# if-else with one-liners
if choice == 1: print('This is choice 1')
else: print('This is a choice other than 1')

# if-else if with one-liners
if choice == 1: print('This is choice 1')
elif choice == 2: print('This is choice 2')

# if-else if-else with one-liners
if choice == 1: print('This is choice 1')
elif choice == 2: print('This is choice 2')
else: print('This is a choice other than 1 and 2')

# Multiple simple statements on a single line have to be separated by a semicolumn (;) except for the last one on the line
if choice == 1: print('First statement'); print('Second statement'); print('Third statement')

Usually it is not recommended to pack too many statements on a single line because then you lose one of the big features of Python - readability of the code.

Notice also that the above examples can also easily be applied to for and while . You can go even further as to do some crazy nesting of one-liner if blocks if you use the ternary conditional operator .

Here is how the operator usually looks:

flag = True
print('Flag is set to %s' % ('AWESOME' if True else 'BORING'))

Basically, it creates a simple if-else statement. You can embed it with one of your one-liners if you need more branching (but not complex one).

I hope this clarifies the situation a bit and what is allowed and not allowed. ;)

I've been getting this error even when the indentation looked correct.

Viewing in Notepad++ there is an option to see white spaces and Tabs. The error was caused by mixing spaces and tabs to create indentation. Replacing Tabs with spaces in every line helped to get rid of an error.

Actually, this is a Python IDLE UI issue: Once you hit Enter after the if block finishes, next the else statement is already in intent with the if statement. There isn't any need to provide any tabs or spaces to make indentation. Below is the image for reference.

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM