python - error when trying to use pass keyword in one line if statement -
stumped 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 not if
statement, rather expression (i mean, print
statement, rest being interpreted expression, fails). expressions have values. pass
doesn't, because it's statement.
you may seeing 2 statements (print or pass
), interpreter sees differently:
expr = "no remainder" if 5% 2 == 0 else pass print expr
and first line problematic because mixes expression , statement.
a one-line if
statement different thing:
if 5 % 2 == 0: print "no remainder"
this can called one-line if
statement.
p.s. ternary expressions referred "conditional expressions" in official docs.
a ternary expression uses syntax tried use, needs 2 expressions , condition (also expression):
expr1 if cond else expr2
and takes value of expr1
if bool(cond) == true
, expr2
otherwise.
Comments
Post a Comment