Reputation: 7530
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
Upvotes: 2
Views: 14683
Reputation: 3222
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.
Upvotes: 3
Reputation: 718
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':
Upvotes: 0