In Python, True
and False
represent the boolean values.
In programming code, sometimes it is necessary to determine whether an expression is True
or False
.
When you execute an expression with a specific condition, Python returns a boolean value, either True
or False
.
print(2 > 3)
print(2 == 3)
print(2 < 3)
False
False
True
In the above example, the condition expressions returned True
and False
boolean values.
The first and second conditions check two is greater than three (2 > 3
) and two is equal to three(2 == 3
), respectively, and neither condition is true, so the boolean value returned is False
.
In the third condition statement, we checked two is less than three (2 < 3
), and the condition is satisfied, so the boolean value True
returned.
With an if statement, blocks are executed based on the returned boolean value True
or False
.
number_a = 2
number_b = 3
if number_a > number_b:
print("number_a is greater")
else:
print("number_b is greater")
number_b is greater
In the above example, we are checking number two is greater than number three (2 > 3
), so the output is "number_b is greater"
.
The bool()
constructor function returns True
or False
when you use it on any value or variable.
print(bool(2))
print(bool("Hello world"))
number = 2
text = "Hello world"
print(bool(number))
print(bool(text))
True
True
True
True
In Python, a value is evaluated to True if it has some sort of content.
The numeric value is True, except 0.
String text is True, except for empty strings.
A list, tuple, set, and dictionary are True, except empty ones.
print(bool(10))
print(bool("Hi"))
print(bool(["Red", "Blue", "Green"]))
print(bool(("Red", "Blue", "Green")))
print(bool({"Red", "Blue", "Green"}))
print(bool({"name": "Google", "country": "USA"}))
True
True
True
True
True
True