An error occurred while trying to use the pass keyword on one line if the statement

that it works:

if 5 % 2 == 0: print "no remainder" else: pass 

but not this:

 print "no remainder" if 5% 2 == 0 else pass SyntaxError: invalid syntax 
+4
source share
1 answer

The latter is not an if expression, but an expression (I mean, print is an instruction, and the rest is interpreted as an expression that does not execute). Expressions matter. pass no, because this is a statement.

You can see this as two statements ( print or pass ), but the interpreter sees it differently:

 expr = "no remainder" if 5% 2 == 0 else pass print expr 

and the first line is problematic because it mixes the expression and the operator.

The one-line if is different:

 if 5 % 2 == 0: print "no remainder" 

this can be called a one-line if .

PS Ternary expressions are called conditional expressions in official documents .

The triple expression uses the syntax you tried to use, but it needs two expressions and a condition (also an expression):

 expr1 if cond else expr2 

and it takes the value expr1 if bool(cond) == True and expr2 otherwise.

+10
source

All Articles