I've been studying Python for a few weeks and I came across an interesting video on programming fundamentals that explains De Morgan’s law. The law comes from a field of Math called Boolean algebra.
Although that's not something you'll face on a daily basis in programming - at least not with the theorem itself, having the understanding of these concepts can be super helpful when coding, specifically when compounding conditions. Which is something we do a lot as developers.
Basically the law says according to Wikipedia that “The negation of a disjunction is the conjunction of the negations” and “The negation of a conjunction is the disjunction of the negations”.
Which we can summarize in Python expressions like that:
not (x or y) == not x and not y
not (x and y) == not x or not y
Note one: like in math, when we multiply a set of factors between parentheses by a single factor (e.g. 2(x + 3)) we kinda distribute the factor by multiplying it by all elements inside the parentheses. This case is not different.
Note two: once we distribute the "not" to the operators (and/or) is the simple operation of negating it and transforming it into the opposite operator (what is "and" becomes "or" and vice versa).
And why can understanding these simple expressions be useful?
Because once you do it you also understand the importance of truth tables. Truth tables can be used to represent all the possible values of conditional statements and its possible results. Which means we get all the possible scenarios for if statements and check if the statement we create expresses what we need.
So we can go through a simple example for better understanding. Let's consider the following expression:
x and y or z
If we create a truth table containing all possible values for x, y and z we'll have something like this:
We got eight combinations where five of them evaluate to
Easy, right? And for a simple example might be obvious. But conditionals can become a more complex scenario depending on the context and it's important to create these validations to make sure the condition you've created evaluates exactly what you expect.
Latest comments (0)