2

Can someone say why this doesn't work in Python? Is it simply invalid syntax or is there more to it?

arr[0] += 12 if am_or_pm == 'PM'

The error message:

  File "solution.py", line 13
    arr[0] += 12 if am_or_pm == 'PM'
                               ^
SyntaxError: invalid syntax 

This works:

if am_or_pm == 'PM': arr[0] += 12
lospejos
  • 1,976
  • 3
  • 19
  • 35
M3RS
  • 6,720
  • 6
  • 37
  • 47
  • 3
    That's not valid syntax. Maybe you're thinking of [ternary conditional operation](http://stackoverflow.com/questions/394809/does-python-have-a-ternary-conditional-operator)? `arr[0] += 12 if am_or_pm == 'PM' else 0` – Ted Klein Bergman Mar 11 '17 at 10:09
  • for better readability you may use `if` in a separate line, but the ternary conditional operator Ted suggested is fine as well. – Nicolas Heimann Mar 11 '17 at 10:23
  • Thanks guys, that helps. So I either need to specify an 'else' branch to make it a ternary operation or go with the classic if syntax. Thanks again! – M3RS Mar 11 '17 at 13:09
  • @Andras Exactly. The reason is that the conditional expression is _an expression_. Leaving out the `else` would result in the "expression" having no defined value; e.g., what should `print('hi' if False)` sensibly do (if we refrain from using `None` everywhere automatically, which is a design choice)? – phipsgabler Mar 11 '17 at 13:14

2 Answers2

3

There is surely a kind of usage in Python that the if and else clause is in the same line. This is used when you need to assign a value to a variable under certain conditions. Like this

a = 1 if b == 1 else 2

This means if b is 1, a will be 1, else, a will be 2.
But if and else must all be written to form the valid syntax.

Hou Lu
  • 3,012
  • 2
  • 16
  • 23
0

python doesn't have semicolon. So there is break line into the same line. python consider code into a same line that written in a line. so here a expression and a conditional statement in a same line that is not valid. python interpreter doesn't recognize what the code exactly mean. you can use separate line for this.

arr[0] += 12 
if am_or_pm == 'PM':