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...
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.
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.
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.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With