We can use if-else like this:
statement if condition else statement
but there are some problems here and I can't understand why.
If I run count += 1 if True else l = []
(count is defined already), then it raises an error:
File "<ipython-input-5-d65dfb3e9f1c>", line 1
count += 1 if True else l = []
^
SyntaxError: invalid syntax
Can we not assign a value after else?
When I run count += 1 if False else l.append(count+1)
(note: count = 0, l = []), an error will be raised:
TypeError Traceback (most recent call last)
<ipython-input-38-84cb28b02a03> in <module>()
----> 1 count += 1 if False else l.append(count+1)
TypeError: unsupported operand type(s) for +=: 'int' and 'NoneType'
and the result of l is [1]
.
Using the same conditions, if I use an if-else block, there are no errors.
Can you explain the difference?
The conditional operator – also known as the ternary operator – is an alternative form of the if/else statement that helps you to write conditional code blocks in a more concise way. First, you need to write a conditional expression that evaluates into either true or false .
The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.
If the condition is short and the true/false parts are short then a ternary operator is fine, but anything longer tends to be better in an if/else statement (in my opinion). Save this answer.
A ternary operator takes three arguments. The first one (1st) is the condition, the second one (2nd) is executed if the condition is true, and the third one (3rd) is executed if the condition is false. In layman's term, it's just an {if-else} statement in one (1) line!
The "conditional expression" A if C else B
is not a one-line version of the if/else statement if C: A; else: B
, but something entirely different. The first will evaluate the expressions A
or B
and then return the result, whereas the latter will just execute either of the statements A
or B
.
More clearly, count += 1 if True else l = []
is not (count += 1) if True else (l = [])
, but count += (1 if True else l = [])
, but l = []
is not an expression, hence the syntax error.
Likewise, count += 1 if False else l.append(count+1)
is not (count += 1) if False else (l.append(count+1))
but count += (1 if False else l.append(count+1))
. Syntactically, this is okay, but append
returns None
, which can not be added to count
, hence the TypeError.
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