Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it preferable to use an "else" in Python when it's not necessary?

I actually use Python and Flask for my devblog. I know that depending of the language, it is advisable to use a explicit else when it is not obligatory, but I don't know how it's work in Python.

By example, I have a a function with a if that return something if the statement is true. So, The else is not necessary because with or without it, the execution continue normally.

def foo(bar):
    if not isinstance(foo, list):
        return "an error"
    else: # not necessary 
        return "something"

So, I should use it like this, or like :

def foo(bar):
    if not isinstance(foo, list):
        return "an error"

    return "something"
like image 584
vildric Avatar asked Feb 13 '13 00:02

vildric


People also ask

Is it necessary to use else with if in Python?

If you require code to run only when the statement returns true (and do nothing else if false) then an else statement is not needed. On the other hand if you need a code to execute “A” when true and “B” when false, then you can use the if / else statement.

Is else mandatory in Elif Python?

The if statements can be written without else or elif statements, But else and elif can't be used without else.

Is it mandatory to use the else clause with every for while and if statement?

else clause is optional in if , for , while , and try block. Only one suite will be executed in the if statement. [either if-suite or elif-suite or else-suite). else clause is executed if there is no exception raised in the try block.

What should I put after Python else?

Python allows the else keyword to be used with the for and while loops too. The else block appears after the body of the loop. The statements in the else block will be executed after all iterations are completed. The program exits the loop only after the else block is executed.


1 Answers

From Chromium's style guide:

Don't use else after return:

# Bad
if (foo)
  return 1;
else
   return 2;

# Good
if (foo)
  return 1;
return 2;

return foo ? 1 : 2;
like image 141
skeller88 Avatar answered Oct 20 '22 05:10

skeller88