Python Boolean

Boolean represents one of two values: True or False.

Boolean values

In programming, you usually need to know whether an expression is True or False.

You can calculate any expression in Python and get one of two answers, either True or False.

When comparing two values, the expression will be evaluated, and Python returns a boolean answer:

Instance

print(8 > 7)
print(8 == 7)
print(8 < 7)

Run Instance

When running a condition in an if statement, Python returns True or False:

Instance

Print a message based on whether the condition is true or false:

a = 200
b = 33
if b > a:
  print("b is greater than a")
else:
  print("b is not greater than a")

Run Instance

Evaluate values and variables

The bool() function allows you to evaluate any value and return True or False for you.

Instance

Evaluate strings and numbers:

print(bool("Hello"))
print(bool(10))

Run Instance

Instance

Evaluate two variables:

x = "Hello"
y = 10
print(bool(x))
print(bool(y))

Run Instance

Most values are True

Almost all values will be evaluated as True if there is some content.

Any string is True except for an empty string.

Any number is True except for 0.

Any list, tuple, set, or dictionary is True except for an empty list.

Instance

The following examples will return True:

bool("abc")
bool(123)
bool(["apple", "cherry", "banana"])

Run Instance

Some values are False

In fact, except for empty values (such as ()、[]、{}、""、number 0 and value None), there are few values that will be evaluated as False. Of course, the calculation result of the value False is False.

Instance

The following example will return False:

bool(False)
bool(None)
bool(0)
bool("")
bool(())
bool([])
bool({})

Run Instance

In this case, the calculation result of a value or object is False, that is, if the object is generated by a class with the __len__ function and the function returns 0 or False:

Instance

class myclass():
  def __len__(self):
    return 0
myobj = myclass()
print(bool(myobj))

Run Instance

The function can return boolean

Python has many built-in functions that return boolean values, such as the isinstance() function, which can be used to determine whether an object has a certain data type:

Instance

Check if the object is an integer:

x = 200
print(isinstance(x, int))

Run Instance