Booleans represent one of two values: True or False. In programming you often need to know if an expression is True or False.
1. True and False Values
You can evaluate any expression in Python, and get one of two answers, True or False.
When you compare two values, the expression is evaluated and Python returns the Boolean answer:
print(10 > 9) # True
print(10 == 9) # False
print(10 < 9) # False
When you run a condition in an if statement, Python returns True or False:
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
2. Comparison Operators
Comparison operators are used to compare two values, always resulting in a Boolean value.
==: Equal!=: Not equal>: Greater than<: Less than>=: Greater than or equal to<=: Less than or equal to
x = 5
y = 8
print(x == y) # False
print(x != y) # True
3. bool() Function
The bool() function allows you to evaluate any value, and give you True or False in return.
print(bool("Hello")) # True
print(bool(15)) # True
Almost any value is evaluated to True if it has some sort of content.
- Any string is
True, except empty strings. - Any number is
True, except0. - Any list, tuple, set, and dictionary are
True, except empty ones.
4. Falsy Values
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.
print(bool(False)) # False
print(bool(None)) # False
print(bool(0)) # False
print(bool("")) # False
print(bool(())) # False
print(bool([])) # False
print(bool({})) # False
Functions can return a Boolean
You can create functions that return a Boolean Value:
def myFunction():
return True
if myFunction():
print("YES!")
else:
print("NO!")
Discussion
Loading comments...