'return' in inline if/else not working

If:
b = 5

Then this code works fine:

  if b > 2:
            return False
        else:
            return True

but this doesn’t:
return False if b > 2 else return True

I thought these 2 were functionally equivalent to each other, but I get told ‘this code is unreachable’ about ‘return True’ in the inline version. Not sure why it would be unreachable, so these 2 ways of formatting if/else must be different. Why is that?

Ofcourse it doesn’t - the inline-condition only applies to the recent value (False), not the entire statement (return False).

Also if you return True/False, chances are you can skip the entire if-else-condition. Just return the statement directly.

I’m not sure what you mean in your first paragraph, can you expand on that, or rephrase it a bit.
As the spec for the program requires returning True or False, I tried this, which works.

x = False if b > 2  else x = True
return x

Python read this as
return (False if b > 2 else return True)
Meaning it will try to return return True for the else - hence it fails.

Also I put your “which works” into Python and it doesn’t work on my end. Dunno if you got another Python version.
Anyway, here is the correct syntax:

b = 0
x = 2 + 3 if b>2 else 1
# x = 1

Thanks. Yes, my ‘which works’ doesn’t work here either, no idea what happened there.
So the upshot here is that ‘return True/False’ doesn’t belong in inline if/else statements? Or that boolean values can’t be assigned in inline if/else statements? Not sure what to take away from this.

Let’s add an explanation to my example:

x = 2 + 3 if b>2 else 1
# is the same as
if b>2:
  x = 2+3
else:
  x = 1

That’s why b=0 resulted in x=1. The if-else only affected the calculation, not the entire assignment.
You could use any kind of value you want, including boolean :wink:
However the inline has some limitations compared to the normal if-else. I’ll have to look at the documentation on what exactly it can and cannot do. But basically, it’s there to choose inbetween different values and thus you cannot put statements in there, that don’t produce a value.

2 Likes

Thanks, the last sentence sums up what I can and can’t do with these statements. Thanks!

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.