Hey!
I’m learning Python and I have a simple question about not.
In which case not could be used in a real situation? I don’t understand why I should be able to invert my bool. Can you provide a real-life example? thanks!
Hey there and welcome to the forums! There are often times when you want to make something happen if something is not True
.
As an example lets say we are working on an interface for a house rental company. They want their users to be able to come online and find out what houses are available and in their data they store their available homes in a list. The program loops through the loop and shows users the available homes:
houses_available = ['this house', 'this other house', 'another house']
for house in houses_available:
print(house)
But now if there are no houses available the user may just be granted with a blank screen and no explanation. Here we can learn that an empty list returns a False
value and an if
can be implemented to inform users if no house is open:
houses_available = []
if not houses_available:
print("Sorry, no houses available")
else:
for house in houses_available:
print(house)
Other uses can be found when pairing not
with in
:
natural_numbers = [1, 2, 4, 5]
if 3 not in natural_numbers:
print("You forgot 3 :(")
I actually used not
earlier when showing a user how to remove duplicate items from a list:
lst = ["Cole", "Kip", "Chris", "Sylvana", "Chris"]
def unique(lst):
result = []
for i in lst:
if i not in result:
result.append(i)
return result
print(unique(lst))
Thanks! Really clear examples, I think during the lesson is talking about of cases where we want to invert a True. why not use directly False then?
It can be thought of as semantic shorthand. In a filter of large items our brains easily think of if this is not what we want
instead of conditions for what we want are false
. More deeply, its inclusion is because in terms of prepositional logic and boolean algebra, it’s standard to have an inversion operation (see DeMorgan’s Law).
In some languages they use a !
to invert, so:
if (!is_fresh(food)){
throw_out(food);
}
or in python
if not is_fresh(food):
throw_out(food)
Notice how it’s more rhetorical to write:
if is_fresh(food) == False:
throw_out(food)
When we read it, we actually have to think back to the first part of the condition to fully understand it.
In more complicated examples (thinking back to math here) it can also largely simplify things:
not A or not B or not C or not D
is equivalent to
not (A and B and C and D)
(by DeMorgan's Law)
the more complicated the inner expressions are, the more useful these type of simplifications become.
thanks, really exhaustive explanation