1

I am trying to use a ternary condition in my program as follows:

c = 12
(print c) if (c == 10) else (print 'c is not 10')

However, this raises a syntax error. What seems to be wrong here?

2
  • 3
    You can only have expressions, not statements, in a ternary expression. Commented Jul 3, 2016 at 7:27
  • BTW, in Python 3 the following works: c = 12 ; (print (c)) if (c == 10) else (print ('c is not 10')) Commented Jul 3, 2016 at 16:28

2 Answers 2

4

You would do it like this:

print c if c == 10 else 'c is not 10'

The parenthesis are unnecessary, and you must start with the "print"; Python cannot make the whole command a conditional the way Perl can.

There is no Python equivalent of Perl's:

print "Done!" if $done;
Sign up to request clarification or add additional context in comments.

1 Comment

The quote was always supposed to be there. Edited my code in the original post.
0

you shall do print(c) instead of (print c)

1 Comment

c = 12 print(c) if (c==10) else print('not c') still gives syntax error. Its not about parenthesis as Will mentioned in his answer.

Your Answer

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.