stumped that this 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
stumped that this 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
The latter is not an if
statement, rather an expression (I mean, print
is a statement, but the rest is being interpreted as an expression, which fails). Expressions have values. pass
doesn't, because it's a statement.
You may be seeing it 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 an expression and a statement.
A one-line if
statement is a different thing:
if 5 % 2 == 0: print "no remainder"
this can be called a one-line if
statement.
P.S. Ternary expressions are referred to as "conditional expressions" in the official docs.
A ternary 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 of expr1
if bool(cond) == True
and expr2
otherwise.