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.
解决方案
It lets you convert any Python value to a boolean value.
Sometimes you want to store either True or False depending on another Python object. Instead of:
if python_object:
result = True
else:
result = False
you simply do:
result = bool(python_object)
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 all False, the rest is True.
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:
class Tree(object):
def __init__(self, children):
self.children
def has_children(self):
return bool(self.children)
Now Tree().has_children() will return True when self.children is not empty, False otherwise.