Python – Booleans

Python – Booleans: Many times in programming, a user will want a data type that represents True and False values. Python includes a bool data type for this, which accepts True or False values.

Boolean Values

When a Python expression or two values are compared, the result is a Boolean answer: True or False values.

Example:

To acquire the boolean result, an expression is evaluated and two values are compared in the example below.

x = 10
y = 25
print(x > y)

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

The output of the above code will be:

False
x is less than y.

Python bool() function

The bool() method in Python returns a boolean value for an object. Everything in Python is an object, and when an object is supplied as an argument to the bool() method, it always returns True unless the following conditions are met:

Syntax

bool(object)

Example:

The bool() method is used on variables called MyString, MyList, and my number in the example below to return the Python – Booleans value of these objects. Due to the fact that these objects are either empty or None, the result is False.

MyString = ""
print(bool(MyString))

MyList = []
print(bool(MyList))

MyNumber = None
print(bool(MyNumber))

The output of the above code will be:

False
False
False

Example:

The bool() method is used on variables MyString, MyList, and MyNumber to return True in the example below.

MyString = "Hello"
print(bool(MyString))

MyList = [1, 2, 3]
print(bool(MyList))

MyNumber = 15
print(bool(MyNumber))

The output of the above code will be:

True
True
True

Boolean return from Functions/Methods

Many built-in functions and methods in Python return a boolean value, such as the isupper() method, which is used to determine whether or not a string is in uppercase. Similarly, the instance() method is used to determine whether or not an object belongs to a certain data type. Take a look at the sample below.

MyString = "Hello"
print(MyString.isupper())

print(isinstance(MyString, str))

The output of the above code will be:

False
True

To acquire a boolean result, you may alternatively utilise a user-defined function. In the example below, a user-defined function named equal() is used to compare two numbers and returns true if they are equal, and false otherwise.

def equal(a, b):
  if a == b:
    return True
  else:
    return False

print(equal(10,25))

The output of the above code will be:

False

Also Read: Java – Booleans

Leave a Reply

Your email address will not be published.