Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if or elif either true then do something

this is just for academic interest. I encounter the following situation a lot.

either_true = False if x:   ...do something1   either_true = True elif y:   ...do something2   either_true = True if either_true:   ..do something3 

is there any pythonic way of doing it, or in general better programming way of doing it. Basically do something3 executes only if or elif is true.

like image 541
Shh Avatar asked Feb 13 '14 14:02

Shh


People also ask

Does Elif run if if is true?

elif ConditionThe elif block is executed if the specified condition evaluates to True .

When should you use an Elif statement?

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.

How does if Elif and else work in Python?

The if-elif-else statement is used to conditionally execute a statement or a block of statements. Conditions can be true or false, execute one thing when the condition is true, something else when the condition is false. Contents: if statement.

What is if-Elif-else statement?

If-elif-else statement is used in Python for decision-making i.e the program will evaluate test expression and will execute the remaining statements only if the given test expression turns out to be true. This allows validation for multiple expressions.


1 Answers

You could also omit the either_true flag completely if doSomething3 is a single line of code (e.g. a function call):

if x:   ..do something 1   ..do something 3 elif y:   ..do something 2   ..do something 3 

It maintains the nice property of evaluating x and y at most once (and y won't be evaluated if x is true).

like image 82
Frerich Raabe Avatar answered Sep 18 '22 00:09

Frerich Raabe