When it is being used in everyday coding? I am learning Python using this tutorial. What am I referring to is described here (middle of the page), but I can't get it. I understand the principles of using True and False, but I don't get when (or do) we actually use the bool()
function in practice while writing our code. It would help me if you give the everyday, practical example of bool()
in code.
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
Converts a value to a boolean.
To understand what
bool()
does we need to first understand the concept of a boolean.A boolean variable is represented by either a 0 or 1 in binary in most programming languages. A 1 represents a "True" and a 0 represents a "False"
The number 1 is different from a boolean value of True in some respects. For example, take the following code:
Notice that 1 is different than True according to Python. However:
When we use the
bool()
function here, we convert 1 to a boolean. This conversion is called "casting". Casting 1 to boolean returns the value of "True".Most objects can be cast to a boolean value. From my experience, you should expect every standard object to evaluate to True unless it is 0, None, False or an empty iterable (for example: "", [], or {}). So as an example:
Lastly, a boolean prints as either "True" or "False"
bool
exposes the fact that Python allows for boolean conversions to things that you wouldn't typically consider to be True or False.An example of this is lists. If
len(my_list)
would be greater than 0, it also treats this asTrue
. If it has no length -- iflen()
would return 0 -- it isFalse
. This lets you write code like this:If
check_list_for_values
returns a list that has length greater than 0, then it prints "got a match" because it evaluates toTrue
. If there is no length to the list that would be returned...Then there will be nothing printed, because it evaluates to
False
.It lets you convert any Python value to a boolean value.
Sometimes you want to store either
True
orFalse
depending on another Python object. Instead of:you simply do:
How Python objects are converted to a boolean value, all depends on their truth value. Generally speaking,
None
, numeric 0 and empty containers (empty list, dictionary, set, tuple, string, etc.) are allFalse
, the rest isTrue
.You use it whenever you need an explicit boolean value. Say you are building an object tree, and you want to include a method that returns
True
if there are children in the tree:Now
Tree().has_children()
will returnTrue
whenself.children
is not empty,False
otherwise.