If a negative evaluation in the if argument causes a return call inside the function / method, what is more recommended in Python to nest if statements or use a reverse evaluation and call the return function? eg:.
if required_condition_1: if required_condition_2: if required_condition 3: pass return 'error for condition 3' return 'error for condition 2' return 'error for condition 1'
Or:
if not required_condition_1: # preparation... return 'error for condition 1' if not required_condition_2: # preparation... return 'error for condition 2' if not required_condition_3: # preparation... return 'error for condition 3' # if runtime reaches this point it means that it has passed all conditions
Imagine that you have to register a user and you need different conditions to satisfy. A user will only be registered if they are all satisfied, but error messages depend on which condition fails.
My assumption is that in other cases, as the user mentions in the answer section, other actions may be taken if any condition fails. Then I think I should attach ifs. However, I will only return an error message, so I think the second option is preferable.
I also thought about the statement:
try: assert(required_condition_1) try: assert(required_condition_2) # do tasks except AssertionError: # error for condition 2 except AssertionError: # error for condition 1
Despite the fact that I think this last method is not highly recommended, as in exception handling. Just as the SO user mentions :
If the code is correct, the prohibition of one-time events, hardware failures and such, no statement will ever fail. This is why the behavior of the program for the end user should not be affected. Especially, they say they cannot help but cope even in exceptional program conditions. It just never happens. If this happens, the programmer must be locked for it.
I know that this may seem mainly based on opinions, but for me it is not , because all languages have stylistic recommendations that create a more stable, scalable and readable environment depending on its characteristics and functionality. I would like to know what if there is a recommended way to address this issue within methods and , most importantly, why .