Python bool()
Function: Convert Values to Boolean
The bool()
function in Python converts a value into a boolean (True
or False
). It follows standard truthy and falsy rules.
Example
print(bool(1)) # True
print(bool(0)) # False
print(bool("Hello")) # True
print(bool("")) # False
Non-empty values return True
, while empty or zero-like values return False
.
Syntax
bool(value)
- value: Any Python object (number, string, list, etc.).
- Returns:
True
if the value is truthy,False
if it’s falsy.
Why Use bool()
?
1. Checking if a Variable Has a Value
bool()
helps determine if a variable is empty or zero.
user_input = ""
if not bool(user_input):
print("No input provided.")
# Output: No input provided.
2. Simplifying Conditions
Instead of checking if x != 0
, just use if x:
.
balance = 100
if balance:
print("Account is active.") # Runs because balance is truthy
3. Filtering Data
Remove falsy values from a list using filter()
.
data = [0, 1, "", "Python", [], {}]
filtered_data = list(filter(bool, data))
print(filtered_data)
# Output: [1, 'Python']
4. SQL Use Case: Converting to Boolean Before Storing
Databases often store booleans as 0
and 1
. Use bool()
before inserting values.
is_active = bool(5) # Any non-zero number is True
print(f"INSERT INTO users (active) VALUES ({int(is_active)});")
# Output: INSERT INTO users (active) VALUES (1);
Key Notes
- ✔ Falsy values:
0
,""
,[]
,{}
,None
,False
all returnFalse
. - ✔ Truthy values: Everything else returns
True
. - ✔ Useful for conditions: Makes
if
statements cleaner. - ✔ Common in SQL and APIs: Ensures consistency when handling boolean data.
By using bool()
, you can write cleaner, more efficient code for checking values, filtering data, and working with databases. 🚀