Indentation of IF-ELSE block in python

喜你入骨 提交于 2019-12-01 08:24:54
Levon

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

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).

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.

" -- 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 thebody 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 loose 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'))

What this does is basically create a simple if-else statement. You can embed it with one of your one-liners if you need more branching (but not complex one).

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

I've been getting this error even 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 an Python IDLE UI issue: Once you hit enter after if block finishes, next else statement is already in intent with if statement. No need to provide any tabs or spaces to make indentation. Below is the image for reference.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!