Python bool()

Python’s bool() function converts a given value into Boolean(True or False) using the standard truth testing procedure.

bool() Syntax 

The syntax of bool() method is 

bool([value])

bool() Parameters

The bool() method can take one argument on which the standard truth testing procedure is applied.

The parameter is optional for the bool() function. If you do not pass any value by default, it returns False.

bool() Return Value

The bool() function returns 

  • True if the parameter of the value passed is True
  • False if the parameter of the value passed is False or if the value is omitted

There are few exceptional cases where the bool() method returns False. Following are the values:

  • None
  • False
  • Empty sequence such as (), ‘ ‘,[] etc
  • Zero of any numeric type such as 0, 0.0, 0j
  • Empty mapping such as {}
  • If Objects of Classes having __bool__() or __len()__ method, returning 0 or False

Example of bool() function in Python

# Python program to demostrate bool() function

# Returns False as x is False
x = False
print(x, 'is ',bool(x))

# Returns True as x is True
x = True
print(x, 'is ',bool(x))

# Returns False as x is an empty sequence
x = ()
print(x, 'is ',bool(x))

# Returns False as x is an empty mapping
x = {}
print(x, 'is ',bool(x))

# Returns False as x is 0
x = 0.0
print(x, 'is ',bool(x))

# Returns False as x is None
x = None
print(x, 'is ',bool(x))


# Returns True as x is a non empty string
x = 'ItsMyCode'
print(x, 'is ',bool(x))

Output

False is  False
True is  True
() is  False
{} is  False
0.0 is  False
None is  False
ItsMyCode is  True

0 Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

You May Also Like
XOR in Python

XOR in Python

XOR Operator in Python is also known as “exclusive or”  that compares two binary numbers bitwise if two bits are…