-2

What exactly is wrong with the syntax and why in the following piece of code? I've counted the parentheses among other things yet am unable to figure it out.

c = ""
 print("Yes") if c else print("No")

Note: It gives a Syntax error like the one below:

print("Yes") if c else print("No")
                            ^
SyntaxError: invalid syntax
10
  • it works for me.... take a look at your indentation Commented Aug 3, 2018 at 9:29
  • @B001ᛦ How does it work? Commented Aug 3, 2018 at 9:30
  • Possible duplicate of Syntax error in if else statement Commented Aug 3, 2018 at 9:31
  • 4
    print is a statement in python 2. You can't use statements in a conditional. Commented Aug 3, 2018 at 9:31
  • 1
    in Python 2 print "Yes" if c else "No" Commented Aug 3, 2018 at 9:32

1 Answer 1

4

This happens because the print function behaves differently in python2 and python3:
Meanwhile in python3 your code works perfectly, in python2 it raises an error.
This happens because in python2, print is actually a statement and not a function; here you can find a more in-depth QA on the difference between functions and statements.

By the way, you can solve your problem importing the python3 print function from the future:

from __future__ import print_function

c = ""

print("Yes") if c else print("No")

OUTPUT:

No
Sign up to request clarification or add additional context in comments.

Comments

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.