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,9864 gold badges19 silver badges38 bronze badges
asked Mar 11, 2017 at 10:05
4
  • 3
    That's not valid syntax. Maybe you're thinking of ternary conditional operation? arr[0] += 12 if am_or_pm == 'PM' else 0 Commented Mar 11, 2017 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. Commented Mar 11, 2017 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! Commented Mar 11, 2017 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)? Commented Mar 11, 2017 at 13:14

2 Answers 2

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.

answered Mar 11, 2017 at 13:37
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':
answered Mar 11, 2017 at 13:24

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.