user2369440
user2369440

Reputation: 41

Python :: Ternary Operator :: Not able to use multiple statements

I have the scenario something like this.

a = 3
b = 5
c = 7
# using ternary operator now,
print a; c = 1 if a < b else print b ; c = 2

Which raises this error when I use assignment operator on both the sides

SyntaxError: can't assign to conditional expression

If I use it on one side like this, it works fine.

a = 1 ; c = 1 if a < b else b 

So question is How to use multiple statements in Python Ternary Operator?

Upvotes: 2

Views: 4493

Answers (2)

Ali Hassan
Ali Hassan

Reputation: 966

You can not perform multi statement with Ternary expressions. But you can do this. I am not sure whether it will run faster or not.

a = 3
b = 5
c = 7

def onTrue():
    print(a)
    c = 1

def onFalse():
    print(b)
    c = 2

onTrue() if a < b else onFalse

Upvotes: 1

Olivier Melan&#231;on
Olivier Melan&#231;on

Reputation: 22294

Short answer: you cannot have statements in ternary expressions.

A ternary expression is not meant to contain statements, only expressions. In Python2, print is a statement and it is thus a invalid syntax to have it inside a ternary.

c = 1 if a < b else print b
#                   ^^^^^^^ In Python2 `print` is a statement

The purpose of a ternary is to conditionall return a value. So both branches should be expressions that preferably return a value of the same type.

# This is a good use of ternary expressions
c = 1 if a < b else 2

Any other case should probably be using an if-statement.

if a < b:
    c = 1
else:
    print b
    c = 2

Upvotes: 4

Related Questions