Suppose a function (or conditional block) like this:
def es_triangulo_equilatero(lado1, lado2, lado3, angulo1, angulo2, angulo3):
if tres_lados_iguales(lado1, lado2, lado3):
if tres_angulos_iguales(angulo1, angulo2, angulo3):
return True
else:
return False
else:
return False
I would like to know if in all the functions in which the fulfillment of several conditions is required, one condition must always be nested inside the other, and indicate what must happen in the negative cases exhaustively, or on the contrary, there is some cleaner syntax that validates or revokes the fulfillment of all the conditions at the same time.
I've been looking on SO and other sites but there doesn't seem to be much information on it.
Write something like:
is an antipattern , since much more succinctly you can do:
In your case:
You actually don't even need those helper functions:
This is because python "compiles" the expression
a==b==c
and converts it toa==b and b==c
. Not all languages support this feature, beware.Responding to a comment . If the function has to return one thing or another depending on whether the triangle is equilateral or not, it would be best to separate it into two functions, one that detects whether it is equilateral and another that decides what to do. This is following the single responsibility rule , according to which a function must have a clear and single purpose.
By the way, to check if it is equilateral, it is enough to look at the three sides (or the three angles) it is not necessary to verify both things, but to continue with the example, I will not modify that.
Following the single responsibility principle, I would do:
If you don't want to make a separate function to check if it's equilateral, you can still use this trick to make the code easily readable:
Given the interest that the question aroused in its day and now with a little more practice, I answer myself, to broaden and clarify the scope of the question. Without taking any credit from @abulafia, whose answer is immaculate.
If, for example, we have a group of friends who want to go to a nightclub:
This would be rewritten:
Or also:
I take this opportunity to ask your opinion: What principle do you think should prevail, ' explicit is better than implicit ' or ' flat is better than nested '?
I think what you're looking for is the and operator . If you have 2 functions:
And you want to check them in a single if block, you can do
But if you have to do something different in case the one of the sides is true and not the one of the angles than if the one of the angles is true and not the one of the sides, maybe you should separate and nest the if blocks.
In any case, I recommend you take a look at logical operators .