Skip to content
Advertisement

How Does the Multiple Return Syntax Work?

I have a problem where I want to return a value based on a result. But to accomplish that, I would need to have multiple return statements like this:

if w1 > w2: return 'Computer Wins!!'
elif w1 == w2: return 'Tie War!!'
else:
    return 'I Win!!'

But I saw someone syntax like this:

return ('I Win!!', 'Computer Wins!!', 'Tie War!!')[(w1>w2)-(w1==w2)]

So, I am not sure how the second piece of code works. Can you please explain it? Thanks!

Advertisement

Answer

Second method is clever but I would not recommend it for readability sake:

Let’s break the code down


return ('I Win!!', 'Computer Wins!!', 'Tie War!!')[(w1>w2)-(w1==w2)]

Note: True evaluates to 1 and False to 0 in Python.

Cases

If (w1 > w2) is True(1) then necessarily (w1 == w2) is False(0)
-> [(w1 > w2) – (w1 == w2)]
-> [1 – 0] equals [1]
-> Therefore ('I Win!!', 'Computer Wins!!', 'Tie War!!')[1]
-> Results is 'Computer Win!!'

If (w1 > w2) is False(0) then necessarily (w1 == w2) is False(0)
-> [(w1 > w2) – (w1 == w2)]
-> [0 – 0] equals [0]
-> Thus ('I Win!!', 'Computer Wins!!', 'Tie War!!')[0]
-> Results is 'I win!'

If (w1 > w2) is False(0) and (w1 == w2) True (1) then
-> [(w1 > w2) – (w1 == w2)]
-> [0 – 1] equals [-1]
so ('I Win!!', 'Computer Wins!!', 'Tie War!!')[-1] gives the last item, namely 'Tie War!!'

Advertisement