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
2 Answers 2
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.
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':
arr[0] += 12 if am_or_pm == 'PM' else 0
if
in a separate line, but the ternary conditional operator Ted suggested is fine as well.else
would result in the "expression" having no defined value; e.g., what shouldprint('hi' if False)
sensibly do (if we refrain from usingNone
everywhere automatically, which is a design choice)?