In this tutorial, we will learn about Python Boolean. The Booleans data type represent one of two values: True or False.
Boolean Values
In programming, we often need to know if a condition is True or False so that we can perform action based on the results.
We can evaluate any expression to get one of two answers, True or False.
When we compare two values, the expression is evaluated and Python returns the Boolean answer:
Example
print(15 > 19) print(6 == 6) print(11 < 9)
Output
True
False
When we run a condition in an if statement, Python returns True or False:
Example
x = 100 y = 40 if y > x: print("y is greater than x") else: print("y is not greater than x")
Output
Evaluate Values and Variables
The bool() function allows us to evaluate any valueto get True or False in return,
Example
print(bool("Welcome")) print(bool(25))
Output
True
Most Values are True
If any value has some sort of content, it is evaluted to True.
Any number is True, except 0.
Any string is True, except empty strings.
Any set, list, tuple, and dictionary is True, except empty ones.
Example
print(bool("xyz")) print(bool(143)) print(bool(["orange", "mango", "banana"]))
Output
True
True
Some Values are False
In fact, there are not many values that evaluate to False, except empty values, such as (), [], {}, “”, the number 0, and the value None. And of course the value False evaluates to False.
Example
print(bool(())) print(bool([])) print(bool(False)) print(bool(None)) print(bool({})) print(bool(0)) print(bool(""))
Output
False
False
False
False
False
False