Last Updated : 21 Feb, 2025
In Python, bool() is a built-in function that is used to convert a value to a Boolean (i.e., True or False). The Boolean data type represents truth values and is a fundamental concept in programming, often used in conditional statements, loops and logical operations.
bool() function evaluates the truthness or falseness of a given value and returns either True or False. Understanding how bool() works is crucial for writing effective and efficient Python code.
Example:
Python
x = bool(1)
print(x)
y = bool()
print(y)
Syntax of bool() function
Parametersbool([x])
bool()
returns False
by default.The bool() function returns:
In Python, certain values are considered "truth" or "false" based on their inherent properties. Here’s a breakdown:
False Values:
Truth Values:
1
, -1
, 3.14
)."hello"
).[1, 2, 3]
, {"key": "value"}
).
print(bool(True))
print(bool(False))
print(bool(0))
print(bool(1))
print(bool(-1))
print(bool(0.0))
print(bool(3.14))
print(bool(""))
print(bool("Hello"))
print(bool([]))
print(bool([1, 2]))
print(bool({}))
print(bool({"a": 1}))
print(bool(None))
True False False True True False True False True False True False True False
Explanation:
value = 10
if bool(value):
print("The value is truth.")
else:
print("The value is false.")
The value is truth.
Explanation:
bool(value)
function is used to check if value
is truth or false.value
is 10
, which is a non-zero number, bool(value)
returns True
.if
block is executed, and the message "The value is truth." is printed.
class gfg:
def __init__(self, value):
self.value = value
def __bool__(self):
return bool(self.value)
obj1 = gfg(0)
obj2 = gfg(42)
print(bool(obj1))
print(bool(obj2))
Explanation:
g
fg with an __init__
method and a __bool__
method.__bool__
method is a special method in Python that defines the truthiness of an object when bool()
is called on it.bool(obj1)
is called, the __bool__
method of obj1
is invoked, which returns bool(self.value)
. Since self.value
is 0
, bool(obj1)
returns False
.bool(obj2)
returns True
because self.value
is 42
, which is a non-zero number.Here is a program to find out even and odd by the use of the bool() method. You may use other inputs and check out the results.
Python
def check_even(num):
return bool(num % 2 == 0)
num = 8
if check_even(num):
print("Even")
else:
print("Odd")
Explanation:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4