What is Bool in Python? How is the Bool function in Python used? Let’s find out with Quantrimang.com!
In the Python programming language, the bool() function is used to convert a value to a Boolean (True or False) using a standard truth-checking procedure. So how to use the bool() function? We invite you to find out in this article.
Syntax of bool() function
bool([gia_tri])
Parameters of bool() function:
Usually, function parameters bool()
will be a value. It is not required to pass a value to the bool() function, and in case there is no value, the function bool()
will return False.
What value does the bool() function return?
Jaw bool()
returns True or False:
- False: If the value is False or not transmitted.
- True: If the value is True.
The following values will be evaluated by Python as False:
- None
- False
- The number 0 of any numeric data type, such as 0, 0.0, 0j.
- Empty sequences like (), [ ]’ ‘.
- map is empty like { }.
- Object or class has
__bool__()
or__len()__
returns 0 or False.
All values outside the above list are True.
Example of bool() function
ktra = []
print(ktra,'là',bool(ktra))
ktra = [0]
print(ktra,'là',bool(ktra))
ktra = 0.0
print(ktra,'là',bool(ktra))
ktra = None
print(ktra,'là',bool(ktra))
ktra = True
print(ktra,'là',bool(ktra))
ktra="Quantrimang.com"
print(ktra,'là',bool(ktra))
In this program, we will check a series of values, see if the bool() function returns False or True, we have the following output:
[] là False
[0] là True
0.0 là False
None là False
True là True
Quantrimang.com là True
Python bool as keyword
Integration names are not keywords. As for the Python language, they are regular webs. If you bind them, you will override the built-in value.
In contrast, the names True and False are not built-in. They are keywords. Unlike many other Python keywords, True and False are Python expressions. Because they are expressions, you can use them anywhere an expression can be placed, such as 1+1.
You can assign a Boolean value as a variable, but you cannot assign a value to True:
>>> a_true_alias = True
>>> a_true_alias
True
>>> True = 5
File "", line 1
SyntaxError: cannot assign to True
Since True is a keyword, you cannot attach a value to it. Apply the same rule for False:
>>> False = 5
File "", line 1
SyntaxError: cannot assign to False
You cannot assign False because it is a keyword in Python. This way, True and False behave like other constants. For example, you can pass 1.5 to functions or attach it to variables. However, you cannot assign a value to 1.5. The statement 1.5 = 5 is not valid Python. Both 1.5 = 5 and False = 5 are invalid Python code and will cause a SyntaxError when parsed.
The bool()
function in Python is a built-in function used to evaluate a value or expression and return its Boolean value, either True
or False
. Boolean values are fundamental in Python, as they are the backbone of decision-making structures like if
and while
statements. Below is a comprehensive guide to the bool()
function, its behavior, and its applications.
1. Definition and Syntax
The bool()
function is defined as follows:
- Parameters:
The function accepts a single optional argument (value
). If no argument is provided, it returnsFalse
. - Return Value:
The function returns:False
if thevalue
is considered falsey.True
if thevalue
is considered truthy.
2. Truthy and Falsey Values in Python
Python evaluates objects and values as either truthy or falsey when used in a Boolean context. This behavior applies to the bool()
function as well.
2.1 Falsey Values
These are values that evaluate to False
in a Boolean context:
None
: Represents the absence of a value.False
: The BooleanFalse
itself.- Numeric values:
0
,0.0
,0j
(integer, float, and complex numbers). - Empty sequences/collections:
''
(empty string),[]
(empty list),()
(empty tuple),{}
(empty dictionary),set()
(empty set), andfrozenset()
. - Empty ranges:
range(0)
.
2.2 Truthy Values
Any value not listed above is considered truthy, including:
- Non-zero numbers:
1
,-1
,3.14
, etc. - Non-empty sequences:
'abc'
,[1, 2, 3]
,(0,)
, etc. - Objects: Instances of classes (unless they define their own
__bool__()
or__len__()
method that returnsFalse
).
3. Behavior and Examples
Let’s explore how bool()
behaves with different data types and values.
3.1 With Numbers
- Integers:
- Floating-point numbers:
- Complex numbers:
3.2 With Strings
- An empty string is
False
, while any non-empty string isTrue
:
3.3 With Sequences
- Empty sequences are
False
, and non-empty sequences areTrue
:
3.4 With Dictionaries and Sets
- Empty collections are
False
, and non-empty collections areTrue
:
3.5 With None
None
always evaluates toFalse
:
3.6 With Custom Objects
- By default, custom objects are
True
, unless they define a__bool__()
or__len__()
method that explicitly returnsFalse
:
4. Applications of bool()
4.1 Type Conversion
The bool()
function is commonly used to convert values to their Boolean equivalents:
4.2 Conditional Expressions
Although direct evaluation is more common in conditional statements, bool()
can explicitly clarify the intent:
4.3 Input Validation
The function can be used to check whether a user input is valid or not:
4.4 Default Values in Functions
bool()
can evaluate whether to use default or provided arguments:
5. Performance Considerations
The bool()
function is highly optimized for checking the truth value of objects. However, in contexts where a direct truth test (if value
) suffices, using bool()
is redundant and slightly less performant. For example:
6. Customizing Boolean Behavior
As mentioned, objects can override the default truthiness by implementing special methods:
__bool__()
: Should returnTrue
orFalse
.__len__()
: If__bool__()
is not defined, Python checks the length using__len__()
. A length of0
meansFalse
.
Example:
7. Key Points to Remember
- The
bool()
function is a convenient way to evaluate truthiness. - Empty values (like
0
,None
,[]
) areFalse
, while all others areTrue
. - You can customize truthiness for objects using
__bool__()
or__len__()
.
8. Common Mistakes
- Redundant Use: Using
bool()
unnecessarily in conditions. - Confusion with
is
: Remember thatbool(x)
evaluates the truthiness ofx
, whilex is True
checks for identity, which is different.
The bool()
function is straightforward yet powerful, allowing Python to handle a variety of truthiness tests consistently across its rich ecosystem.