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')
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.
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.
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.
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 −
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
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.
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