Boolean in Python
In Python, a boolean is a data type that represents one of two values: either True or False.
True and False are the two built-in boolean values in Python. They are case-sensitive, so you must write them with an uppercase initial letter: True and False.
Example:
x = True
y = False
print(x)
print(y)
Output:
True False
Booleans are used to perform logical operations and make decisions in your code. They are fundamental to controlling the flow of a program through conditional statements like if, elif, and else. When two values are compared, the expression is evaluated and a boolean value is returned.
Example:
x = 10
y = 20
print(x > y)
print(x < y)
print(x == y)
if x > y:
print("x is greater than y")
elif x == y:
print("x is equal to y")
else:
print("y is greater than x")
word1 = "hello"
word2 = "Hello"
result1 = word1 is word2
print("word1 is equal to word2 = ", result1)
result2 = word1 is not word2
print("word1 is not equal to word2 = ", result2)
Output:
False True False y is greater than x word1 is equal to word2 = False word1 is not equal to word2 = True
In Python, the bool() function evaluates any value and return True or False.
Example:print(bool("hello"))
print(bool(1 > 0))
print(bool(10))
print(bool("abc"))
print(bool(0))
print(bool(None))
print(bool(False))
print(bool(""))
print(bool([]))
print(bool({}))
print(bool(()))
Output:
True True True True False False False False False False False