Reputation: 975
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 if-else statements, that are written in single line.
Upvotes: 2
Views: 127
Reputation: 37404
it's nested else-if ,for clarity it can be seen as this
if x == y:
return 0
else:
if x > y:
return 1
else:
return -1
and it would be great if the code is clear and understandable in less possible efforts
So later, what if you want to add one more case in lengthy conditional statements then it can be issue so better option is to use elif
ladder like this
def _comp(total):
if total>90:
return 'Python lover'
elif total>80 and total<=89:
return 'Friend of python'
# elif total>50 and total<=79 added later easily
# return 'you like python' added later easily
else:
return 'python is waiting for you'
Upvotes: 3
Reputation: 32504
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)
Upvotes: 6