Rakesh_K Rakesh_K - 1 month ago 16
Python Question

More than one if-else in single line, how to interpret them?

Well I certainly Understand if-else that are return in single line like

return 0 if x==y else 1


Which translate to

if x==y:
return 0
else:
return 1


I am confused about those statements where if-else occurs multiple time in one line like

def _cmp(x, y):
return 0 if x == y else 1 if x > y else -1


How to interpret and understand multiline if-else statements.

Answer

Introducing parentheses makes it easier to understand.

0 if x == y else 1 if x > y else -1

must be parsed as

0 if x == y else (1 if x > y else -1)