Python bool()
Function
The bool() function in Python is used to convert a value to a Boolean – either True
or False
. It’s a very useful function when you want to check if a value is considered "truthy" or "falsy".
Syntax
bool(value)
Parameters:
value
– Any Python object (optional)
Returns:
True
orFalse
depending on the "truthiness" of the object
Example 1: Convert Numbers to Boolean
print(bool(10)) # True
print(bool(0)) # False
Example 2: Convert Strings to Boolean
print(bool("hello")) # True
print(bool("")) # False
Example 3: Convert Lists and Other Containers
print(bool([1, 2, 3])) # True
print(bool([])) # False
print(bool({})) # False
print(bool(None)) # False
Truthy vs Falsy in Python
These are treated as False when passed to bool()
:
0
0.0
""
(empty string)[]
(empty list){}
(empty dict)set()
(empty set)None
Everything else is considered True.
Use Case: Check if Input is Empty
user_input = input("Enter your name: ")
if bool(user_input):
print("Hello,", user_input)
else:
print("You didn't enter anything!")
Common Mistakes
- Assuming
"False"
(string) is False – it’s actuallyTrue
! - Forgetting that
None
is alwaysFalse
Interview Tip
Understanding what values are considered falsy is important in conditions, loops, and clean code. Python often uses if some_list:
instead of if len(some_list) > 0:
Summary
bool()
converts a value toTrue
orFalse
- Falsy values:
0
,""
,[]
,{}
,None
- Truthy values: everything else
Practice Problem
Write a program to check if the user entered any text. If not, ask them to try again.
text = input("Enter something: ")
if bool(text):
print("You entered:", text)
else:
print("Please enter some text.")