Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 3 and-or vs if-else

Is there any difference between the following?

print(x if x else 'no x available')
# compared to:
print(x and x or 'no x available')
like image 958
Markus Meskanen Avatar asked Apr 29 '14 13:04

Markus Meskanen


People also ask

How do you use if else in Python 3?

Python 3 - IF...ELIF... ELSE Statements. An else statement can be combined with an if statement. An else statement contains a block of code that executes if the conditional expression in the if statement resolves to 0 or a FALSE value. The else statement is an optional statement and there could be at the most only one else statement following if.

What is the difference between if in if and if else?

In if, the statements inside the if block will execute if the condition is true and the control is passed to the next statement after the if block. In the if else, if the condition is true, the statements inside the if block execute and if the condition is false the statements in the else block execute.

What is the difference between IF statements in Python?

Python's if statements make decisions by evaluating a condition. When True, code indented under if runs. Else our program continues with other code. If statements that test the opposite: Python's if not explained. Most Python if statements look for a specific situation. But we can also execute code when a specific condition did not happen.

What is the difference between else and Elif statements in Python?

Similar to the else, the elif statement is optional. However, unlike else, for which there can be at the most one statement, there can be an arbitrary number of elif statements following an if. Core Python does not provide switch or case statements as in other languages, but we can use if..elif...statements to simulate switch case as follows −


2 Answers

Both lines are same as:

print(x or 'no x available')

About second alternative: Always keep in mind, that according to operator precedence and is evaluated first, so it first calculates x and x, which is totally useless - it equals x

like image 181
Ivan Klass Avatar answered Sep 28 '22 18:09

Ivan Klass


In practice they are the same; in theory they are different, but only when the __bool__ method has side effects:

>>> class Weird:
    state = False
    def __bool__(self):
        self.state = not self.state
        return self.state


>>> x = Weird(); print(x if x else 'no x available')
<__main__.Weird object at 0x0000000003513160>
>>> x = Weird(); print(x and x or 'no x available')
no x available

If you run into this theoretical case you have worse problems to worry about.

Also note that:

>>> x = Weird(); print(x or 'no x available')
<__main__.Weird object at 0x00000000035071D0>

so Klass Ivan's answer is technically wrong.

Bottom line, use the if expression as that expresses what you mean much more clearly.

like image 35
Duncan Avatar answered Sep 28 '22 18:09

Duncan