A Boolean can hold just two values: True or False.
Boolean Values
Programs often need to find out whether an expression is True or False.
Python can evaluate any expression and will always answer with one of those two values.
Comparing two values is a common case, and the result is a Boolean:
Example
Output: complete Python program
print(10 > 9)
print(10 == 9)
print(10 < 9)
Example
Choose what to print depending on whether the condition is True or False:
Output: complete Python program
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
Evaluate Values and Variables
Pass any value to the bool() function and it answers with True or False.
Example
Check a string and a number:
Output: complete Python program
print(bool("Hello"))
print(bool(15))
Example
Check two variables:
Output: complete Python program
x = "Hello"
y = 15
print(bool(x))
print(bool(y))
Most Values are True
If a value has some kind of content, it will nearly always count as True.
Strings are True unless they are empty.
Numbers are True unless they equal 0.
Lists, tuples, sets, and dictionaries are True unless they are empty.
Example
Each of these calls returns True:
Output: complete Python program
bool("abc")
bool(123)
bool(["apple", "cherry", "banana"])
Some Values are False
Only a small group of values count as False: empty values such as (), [], {}, and "", the number 0, the value None, and naturally False itself.
Example
Each of these calls returns False:
Output: complete Python program
bool(False)
bool(None)
bool(0)
bool("")
bool(())
bool([])
bool({})
Example
An object can also count as False. This happens when its class defines a __len__ function that returns 0 or False:
Output: complete Python program
class myclass():
def __len__(self):
return 0
myobj = myclass()
print(bool(myobj))
Functions can Return a Boolean
Your own functions can return a Boolean value too:
Example
Print what the function returns:
Output: complete Python program
def myFunction() :
return True
print(myFunction())
Example
Print "YES!" when the function returns True, and "NO!" when it doesn't:
Output: complete Python program
def myFunction() :
return True
if myFunction():
print("YES!")
else:
print("NO!")
Example
Many built-in Python functions return a Boolean as well. One of them is isinstance(), which tells you whether an object has a given data type:
Find out whether an object is an integer:
Output: complete Python program
x = 200
print(isinstance(x, int))