8

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
Lev Levitsky
  • 63,701
  • 20
  • 147
  • 175
Derek Krantz
  • 487
  • 1
  • 6
  • 18
  • 4
    Just a heads up: `pass` keyword here is unnecessary. You could simply write `5 % 2 == 0: print "No remainder"`, and skip the `else: pass` entirely. – msvalkon Apr 19 '13 at 21:53
  • print "no remainder" if 5% 2 == 0 else 0 – Tom Apr 19 '13 at 21:53
  • +1 to what msvalkon said; `else pass` is the same as no `else` clause. Also, the incorrect syntax arises from the use of `print`, not from the `else` – salezica Apr 19 '13 at 21:54
  • but what i'm trying to do is print out the time it took to process every 1000 rows, if it's still iterating up to the next 1000, i don't want anything to happen – Derek Krantz Apr 19 '13 at 21:58
  • @DerekKrantz You just need a plain `if` statement then, like the one in my answer. – Lev Levitsky Apr 19 '13 at 21:59

1 Answers1

17

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.

Lev Levitsky
  • 63,701
  • 20
  • 147
  • 175
  • thanks lev. of course, typing "what is an expression in python" nets this as the top result: http://stackoverflow.com/questions/4782590/what-is-an-expression-in-python – Derek Krantz Apr 19 '13 at 21:55
  • @DerekKrantz After reading the linked post, it appears that expressions are actually statements, too. But anyway, it's enough to understand that and expression is something that has a value. – Lev Levitsky Apr 19 '13 at 22:10