Python bool() Built in Function
The Python bool() function returns a Boolean value (True or False) for a given object. The object can be any data type, such as numbers, strings, lists, tuples, sets, dictionaries, etc. The bool() function follows some rules to evaluate the truth value of an object:
- Any numeric value that is not zero is True. Zero (0) is False.
- Any non-empty string is True. Empty string (‘’) is False.
- Any non-empty collection (list, tuple, set, dictionary) is True. Empty collection ([], (), {}, set()) is False.
- None is always False.
- True and False are keywords that represent the Boolean values.
# Example 1: Convert different data types to Boolean with bool() function
num = 10
print(bool(num)) # Output: True
str = "Hello"
print(bool(str)) # Output: True
lst = []
print(bool(lst)) # Output: False
none = None
print(bool(none)) # Output: False
# Example 2: Use bool() function in conditional statements
name = input("Enter your name: ")
if bool(name):
print("Hello", name)
else:
print("Please enter a valid name")
# Example 3: Use bool() function with logical operators
a = 5
b = 0
c = -3
print(bool(a) and bool(b)) # Output: False
print(bool(a) or bool(c)) # Output: True
print(not bool(b)) # Output: True
If you have any questions about this code, you can drop a line in comment.
Comments
Post a Comment