I know the conditional expression in Python is X if C else Y, but I got some problems in using it.
I have two codes to be compared.
Code 1:
def fun(p):
if len(p) >= 2:
p[1] = 'Ok'
else:
p.append('Ok')
p = [1]
fun(p)
print p
Output of code 1:
[1, 'Ok']
Code 2:
def fun(p):
(p[1] = 'Ok') if (len(p) >= 2) else p.append('OK')
p = [1]
fun(p)
print p
Output of code 2:
(p[1] = 'Ok') if (len(p) >= 2) else p.append('OK')
^
SyntaxError: invalid syntax
I know in code 1, whose format is “if C : X else: Y”, the evaluation order is:
- C
- X
- Y
Code 2 throws a syntax error, the reason may be p[1] doesn’t exist. So I guess the format “X if C else Y” is evaluated as follows:
- X
- C
- Y
But that is only my guess. does anyone know the real reason why code 2 is wrong while code 1 is right?
The reason you have a
SyntaxErroris because Python differentiates between statements and expressions.Assignments, like
are statements and can’t be part of an expression, including the conditional expression. See What is the difference between an expression and a statement in Python? for more info.
Order of evaluation doesn’t come into it —
SyntaxErrors happen before any code is evaluated, when its being parsed.In both
ifstatements and conditional expressions, The order of evaluations is etheror
So, in
or
only the true or the fase statement is evaluated, depending on the truthiness of the condition.