Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: elif or new if?

What is better to use:

if var in X:
    #do_whatever
elif (var in Y):
    #do_whatever2

or:

if var in X:
    #do_whatever
if var in Y:
    #do_whatever2

Assuming var can't be in both X and Y... Is there any rule or common practice? Should I use elif? or a new if? or it doesn't matter??

EDIT: Great answers.. But can I say that if the first statement (#do_whatever) ends with a return or a break; where in its end the other condition will not be tested thus wasting the system resources or causing trouble, it's ok to do whatever.. I guess...

like image 940
amyassin Avatar asked Aug 13 '11 18:08

amyassin


People also ask

Why is it better to use Elif instead of if?

The elif is short for else if. It allows us to check for multiple expressions. If the condition for if is False , it checks the condition of the next elif block and so on. If all the conditions are False , the body of else is executed.

Does Python use Elif or else if?

Python supports nested if, elif, and else condition. The inner condition must be with increased indentation than the outer condition, and all the statements under the one block should be with the same indentation.

Is Elif faster than if Python?

Difference between if and if elif else Python will evaluate all three if statements to determine if they are true. Once a condition in the if elif else statement is true, Python stop evaluating the other conditions. Because of this, if elif else is faster than three if statements.

When should Elif be used in Python?

In Python, elif is short for "else if" and is used when the first if statement isn't true, but you want to check for another condition. Meaning, if statements pair up with elif and else statements to perform a series of checks.


2 Answers

It makes a difference in some cases. See this example:

def foo(var):
    if var == 5:
        var = 6
    elif var == 6:
        var = 8
    else:
        var = 10

    return var

def bar(var):
    if var == 5:
        var = 6
    if var == 6:
        var = 8
    if var not in (5, 6):
        var = 10

    return var

print foo(5)        # 6
print bar(5)        # 10
like image 107
Niklas R Avatar answered Nov 13 '22 22:11

Niklas R


If the second statement is impossible if the first one is true (as is the case here, since you said var can't be in both X and Y), then you should be using an elif. Otherwise, the second check will still run, which is a waste of system resources if you know it's going to false.

like image 35
EdoDodo Avatar answered Nov 13 '22 23:11

EdoDodo