Python Booleans



Python has a bool data type, which takes either True or False values.

Boolean Values  

When an expression is evaluated or two values are compared in Python, it returns the Boolean answer: True or False values.

 An expression is evaluated and two values are compared to get the boolean return.


Example 1

print(9 > 6)
print(9 == 6)
print(9 < 6)

Output

True
False
False

Example 2

x = 9
y = 6

if x > y:
    print("x is greater than y")
else:
    print("y is greater than x")

Output

x is greater than y


bool() function

The Python bool() function returns the boolean value of an object. In Python, everything is an object, and when an object is passed as a parameter in bool() function, it always returns True unless:

  • The object is empty, like [], (), {}.
  • The object is False
  • The object is 0
  • The object is None

Syntax

bool(object)

object = any python object(Required).

The bool() function is used on variables called empty [], {}, (), "", 0, None to return the boolean value of these objects. As these objects are returns False.


Example

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

Output

False
False
False
False
False
False

If in object some content available than bool() function returns True


Example

print(bool("Python"))
print(bool(("Python","Java")))
print(bool(["Python","Java"]))
print(bool({'sub1' :"Python",'sub2' :"Java"}))

Output

True
True
True
True

We can create a function that returns a Boolean Value


Example

def check(a, b):
  if a > b:
    return True
  else:
    return False

print(check(9,6))

Output

True