Best practices on python conditionals

961 Views Asked by At

When it comes to best practices on conditionals, which of the following examples is recommended?

def sum(arg1,arg2):
   if arg1>3:
     return
   else:
     return arg1+agr2

or

def sum(arg1,arg2):
   if arg1<3:
     return arg1+agr2
   else:
     return

Thanks in advance!

1

There are 1 best solutions below

0
On BEST ANSWER

Consider using a ternary expression:

def sum(arg1, arg2):
    return arg1 + arg2 if arg1 < 3 else None

As an addendum, if one of the cases is unexpected or undesirable, I like to follow the guard pattern, which involves checking for these cases first before performing your normal logic.

For example,

def safe_divide(a, b):
    # Check preconditions at top of function definition
    if b == 0:
        return None

    # Checks passed, perform normal logic
    return a / b