Prasanna
Prasanna

Reputation: 4656

string concatenation with nested ternary operator ignores the string

I found differences between the following two statements.

message = "a is " + "greater than" if a > 10 else "less than" if a <10 else "equal to" + " 10"

and

message = "a is " + ("greater than" if a > 10 else ("less than" if a <10 else "equal to")) + " 10"

Could someone explain what is happening here

Upvotes: 0

Views: 247

Answers (1)

khelwood
khelwood

Reputation: 59166

The first is interpreted as:

("a is "+"greater than") if a > 10 else "less than" if a < 10 else ("equal to"+" 10")

See docs: "Conditional expressions have the lowest priority of all Python operations."

That's why you have the option of grouping parts of your expression with parentheses.

Upvotes: 6

Related Questions