I've written the following code which results in SyntaxError: invalid syntax
:
self.vec.append(v1) if v1 else pass
I thought it would do the same thing as this code:
if v1:
self.vec.append(v1)
Just wondering why python does not support this syntax while it supports:
self.vec.append(v1) if v1 else 0
Practical Data Science using PythonMany programming languages support ternary operator, which basically define a conditional expression. Similarly the ternary operator in python is used to return a value based on the result of a binary condition.
Except in very simple cases, you should discourage the use of nested ternary operators. It makes the code harder to read because, indirectly, your eyes scan the code vertically. When you use a nested ternary operator, you have to look more carefully than when you have a conventional operator.
Python ternary operator is the most efficient and faster way to perform the simple conditional statement. It returns the specific block of code depending on whether the condition is true or false.
Ternary Python with Numerical Values In our code, we assign the value 22 to the variable age . We use a ternary operator to check if the value of the age variable is less than 65. Because our customer is 22, the statement age < 65 evaluates to True.
A ternary statement is of the form:
<object> = <object> if <boolean expression> else <object>
But pass
is not an <object>
!
pass
is a keyword, and it is used for flow control (NOOP). For instance, you can't assign pass
to a variable:
>>> x = pass
Syntax Error
In the same way, you can't assign other keywords such as while
to variables either:
>>> x = while
Syntax Error
Also, append
returns None
, which is certainly an <object>
.
>>> print([].append(420))
None
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