Python Booleans


Booleans represent one of two numbers: True or False.


Boolean Values

In the system you usually need to know whether the statement is true or false.

You can check any statement in Python, and get one of two answers, True or False.

When you compare the two values, the speech is tested and Python returns the Boolean response:


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

If you use the status in the statement if, Python returns True or False:


Example

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")


Evaluate Values and Variables

The bool() function lets you check any value, and gives you True or False as a refund,


Example

Evaluate a string and a number:

print(bool("Hello"))
print(bool(15))


Example

Evaluate two variables:

x = "Hello"
y = 15

print(bool(x))
print(bool(y))


Most Values are True

Almost any value is tested to be True if it contains some kind of content.

Any character unit is True, with the exception of blank cables.

Any number is True, except for 0.

Any list, tuple, set, and dictionary is True, except for the blanks.


Example

The following will return True:

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


Some Values are False

In fact, there are not many values ​​that check False, other than empty numbers, such as (), [], {}, "", the number 0, and the value None. And then False value checks False.


Example

The following will return False:

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

One more value, or item in this case, checks that it is False, and that is if you have something made from the section with the function __len__ which returns 0 or False:


Example
class myclass():
  def __len__(self):
    return 0

myobj = myclass()
print(bool(myobj))


Functions can return a Boolean

You can create Boolean Return values:


Example

Print the answer of a function:

def myFunction() :
  return True

print(myFunction())

You can create a code based on the Boolean response function:


Example

Print "YES!" if the function returns True, otherwise print "NO!":

def myFunction() :
  return True

if myFunction():
  print("YES!")
else:
  print("NO!")

Python also has a number of built-in functions that return the boolean value, such as an isinstance() function, which can be used to determine if an object is a specific type of data:


Example

Check if an object is an integer or not:

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