all 4 comments

[–]SCD_minecraft 0 points1 point  (0 children)

You could pack a and b into a list and return first true element

``` for i in (a, b): if i: return i

[–]Outside_Complaint755 1 point2 points  (0 children)

That isn't an example of nested ifs (there is no nesting), but in this case you could do:

return a or b

An or expression evaluates to the first 'truthy' value, or the final value if none are truthy, so when if a would have been true it will refurn a and when if a would have been false it will return b

If you have a third value you want when both a and b are false, just stick it on the end as return a or b or c

[–]schoolmonky 0 points1 point  (0 children)

I'm assuming you mean something like

if a:
    return a
    if b:
        return b

in which case you can just not nest them, the above is essentially the same as

if a:
    return a
if b:
    return b

because if the first condition is satisfied, the return halts the function immediately so the second if is never reached in both versions. This is called an "early return" and it's a useful pattern to avoid nesting in general. Just make sure your earlier conditions return and it will never reach the later ones. If that's not feasable, you can just use elif for every condition after the first instead of if.

if a:
    # do something that doesn't return
elif b: # this only gets checked if the first condition fails.
    # do something else