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.