Home > Mobile >  Better coding practice: if vs if not
Better coding practice: if vs if not

Time:11-01

I have seen a lot of codes and I don't understand what is better practice to use if or if not.

I am putting an example here:

if result:
    return some_value
else:
    raise Exception

OR

if not result:
    raise Exception

return result

I just don't know which one is better practice and why. Would love to get your inputs.

CodePudding user response:

There is no so much difference in this case. Some people can argue for one or another, but for Python there is no much difference.

p.e: I personally like more the second one due its simplicity but some people can argue that first is more difficult to corrupt into bad behavior by human error, where second one can be corrupted easily by adding a new indent in last line by mistake.

CodePudding user response:

The NOT construct is more difficult to understand, and in logic, gives us an infinity of variations.

When you go back to your code and make it more complex, the probability of an mistake increases exponentially.

Thats why code

if result:
    return some_value
else:
    raise Exception

is more relaible

  • Related