0

Here's something simple I thought I would get away with:

foo = True
print('bar') if foo else pass

Which produces:

SyntaxError: invalid syntax

Of course I can just replace pass with None and it will work. I'm just curious: Why doesn't pass work?

xendi
  • 2,332
  • 5
  • 40
  • 64
  • 5
    It's not a ternary statement. It's a ternary *expression*. It chooses between *expressions*, not statements, and `pass` isn't an expression. – user2357112 Sep 10 '20 at 00:07
  • `pass` isn't a variable, it's a statement. You can't use any statements in an if-else expression. You can only use expressions. In Python 3, `print` is a function, and calling it is an expression. – Tom Karzes Sep 10 '20 at 00:07
  • Use the ternary statement to chose between two different values, not actions. – hpaulj Sep 10 '20 at 03:15

2 Answers2

1

pass is a statement and not an expression.

An expression can be used just about anywhere.

Most statements have their special syntax, usually on a line of their own.

For more information about the difference between the two, see this answer.

Bharel
  • 23,672
  • 5
  • 40
  • 80
1

You can do this in a line, as else did nothing, no need of else block.

foo = True
if foo : print('bar') 
ashraful16
  • 2,742
  • 3
  • 11
  • 32