Search code examples
pythonif-statementshorthand

Shorthand 'if' is throwing a syntax error


I have an argparser that has a verbose flag and I'm trying to minimize the amount I have to write to get the verbose output.

This works as expected:

#!/usr/bin/python
verbose=True
print(verbose)
if verbose:
    print("verbose output")

outputs:

$ ./example.py
True
verbose output

but

#!/usr/bin/python
verbose=True
print(verbose)
print("verbose output") if verbose

throws an error:

$ ./example.py
  File "./example.py", line 5
    print("verbose output") if verbose
                                     ^
SyntaxError: invalid syntax

I thought the python had the statement if condition else condition syntax? Have I made some mistake?

$ python -V
Python 3.6.2

Solution

  • The Python if ternary operator syntax requires an else, like so:

    x = 2 if y < 5 else 4