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?
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.
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.
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
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.