In the context of this post, I wonder: why do Python’s Boolean operators
or return values/objects and not only
>>> print(7 or 8)
This functionality is not required when we want to control the flow of a program using
else statements, which are based on the
False value of any statement. So, can someone please provide practical examples that show where this feature of the Boolean operators comes in handy?
and are logical operators, they aren’t Boolean operators.
this is not true, condition also work for truthy/falsy values, for example:
print("7 is a truthy value")
print("7 is a falsy value")
print("0 is a truthy value")
print("0 is a falsy value")
Thanks for correcting my use of language regarding the logical operators.
As for your examples: you show that certain values are considered
False by conditional statements. However, as far as I can see, this doesn’t explain why code like
7 or 8 would (have to) return
7. For the purpose of (your) conditional statements,
7 or 8 could just as well return
Putting any incorrect statements on my behalf aside, I believe the original question still stands then?
See, for example, this post. The checked answer provides several examples leveraging the behavior we are discussing in code.
Here is a discussion with some historical context.
Speaking of history, PEP 285 is instructive: From the mouth (well, keyboard) of Guido himself:
Should we strive to require that Boolean operations (like “if”, “and”, “not”) have a bool as an argument in the future, so that for example “if [ ]:” would become illegal and would have to be written as “if bool([ ]):” ???
Some people believe that this is how a language with a textbook Boolean type should behave. Because it was brought up, others have worried that I might agree with this position. Let me make my position on this quite clear. This is not part of the PEP’s motivation and I don’t intend to make this change.
This PEP does not change the fact that almost all object types can be used as truth values. For example, when used in an if statement, an empty list is false and a non-empty one is true; this does not change and there is no plan to ever change this.
This topic was automatically closed 60 minutes after the last reply. New replies are no longer allowed.