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
Leave a Reply

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

Sign Up for Our Newsletters

Get notified of the best deals on our WordPress themes.

You May Also Like
List of Python free ebooks

List of Free Python Books

Table of Contents Hide Python SuccinctlyPython Data Science HandbookThink Python 2nd EditionAutomate the Boring Stuff with PythonMaking Games with Python & PygameData Structures and Algorithms in Python Google Python Style GuideA…
View Post