Python Boolean

In programming, sometimes we want values to be either True or False which has assigned in programming as Boolean values.

We can compare two values directly which will return True or False accordingly as a Boolean value.

Example

print(10 == 10)
print(10 == 9)
print(10 > 9)
print(10 < 9)

Output

True
False
True
False

In Python, we use the bool() function to check True or False.

bool() function always returns True until we don’t pass something from the following–

  • 0
  • empty string
  • empty list, tuple, dictionary
  • other empty objects like a set
  • anything like a function that returns a function

Example

print(bool(0))  # passing 0
print(bool(""))  # passing an empty string
print(bool([]))  # passing an empty list
print(bool({}))  # passing an empty dict
print(bool(()))  # passing an empty set

Output

False
False
False
False
False

bool() will return True if the value is not an empty one.

Example

print(bool(1))
print(bool(12.2))
print(bool(23j))
print(bool("aString"))
print(bool([1, 2, "Hello"]))
print(bool({"Key":"value"}))

Output

True
True
True
True
True
True