print a if b
File "<stdin>", line 1
print a if b
^
SyntaxError: invalid syntax
Answer
If your print
statement must print an empty line when the expression is false, the correct syntax is:
print(a if b else '')
The reason is you're using the conditional expression which has two mandatory clauses, one when b
is true preceding if
, one when b
is false following else
.
Both clauses are themselves expressions. The conditional expression is also called the ternary operator, making it clear it operates on three elements, a condition and two expressions. In your code the else
part is missing.
However I guess your idea was not to print an empty line when the expression was false, but to do nothing. In that case you have to use print
within a conditional statement, in order to condition its execution to the result of the evaluation of b
.
Details: Expression vs. statement
The conditional statement can be used without the else
part:
The if
statement is a compound statement with further instructions to execute depending on the result of the condition evaluation.
It is not required to have an else
clause where the appropriate additional instructions are provided. Without it, when the condition is false no further instructions are executed after the test.
The conditional expression is an expression. Any expression must be convertible to a final value, regardless of the subsequent use of this value by subsequent statements (here the print
statement).
Python makes no assumption about what should be the value of the expression when the condition is false.
You could have used an if
statement this way:
if b: print(a)
Note the difference:
There is no instructions executed by the if
statement when the condition is false, nothing is printed because print
is not called.
In a print
statement with a conditional expression print(a if b else '')
, print
is always executed. What it prints is the if
conditional expression. This expression is evaluated prior to executing the print
statement. So print
outputs an empty line when the condition is false.
Note your other attempt print(a if b==True)
is just equivalent to the first one.
Since b==True
is syntactically equivalent to b
, I guess Python interpreter just replaces the former by the latter before execution. Your second attempt likely comes down to a repeat of the first one.