AlphaCodingSkills

Python - Booleans


Advertisements

Previous Page Next Page

There are many instances in the programming, where a user need a data type which represents True and False values. For this, 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.

Example:

In the below example, an expression is evaluated and two values are compared to get the boolean return.

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

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

Output

False
x is less than y.

Python bool() function

The Python bool() function is used to return boolean value of an object. In Python, everything is an object and when an object is passed as 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)

Parameters

object Required. Any Python object.

Example:

In the below example, the bool() function is used on variables called MyString, MyList and MyNumber to return boolean value of these objects. As these objects are either empty or None, hence returns False.

MyString = ""
print(bool(MyString))

MyList = []
print(bool(MyList))

MyNumber = None
print(bool(MyNumber))

Output

False
False
False

Example:

In the below example, the bool() function is used on variables called MyString, MyList and MyNumber to return True.

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

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

MyNumber = 15
print(bool(MyNumber))

Output

True
True
True

Boolean return from Functions/Methods

There are many built-in functions and methods in Python which returns a boolean value, like the isupper() method, which is used to check if a string is in uppercase or not. Similarly, the isinstance() function is used to check if an object belongs to specified data type or not. Please see the below example.

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

print(isinstance(MyString, str))

Output

False
True

A user-defined function can also be used to get boolean return. In the below example, a user-defined function called equal() is created to compare two values and returns true if values are equal, else returns false.

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

print(equal(10,25))

Output

False

Previous Page Next Page