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.

Sign Up for Our Newsletters

Get notified of the best deals on our WordPress themes.

You May Also Like
Sort Dictionary By Value In Python

Sort Dictionary by value in Python

Table of Contents Hide Python sorted() function to rescueSyntax: sorted(iterable, key, reverse)Sort a Dictionary by ValueExample 1: Basic Sorting in PythonExample 2 : Sorting different Data Types in PythonExample 3: Sort…
View Post
Python String Isdecimal()

Python String isdecimal()

Table of Contents Hide isdecimal() Syntaxisdecimal() Parametersisdecimal() Return ValueExample 1: Working of isdecimal()Example 2: String Containing digits and Numeric Characters The Python String isdecimal() method is a built-in function that…
View Post
Graphviz'S Executables Not Found

Graphviz’s executables not found

Table of Contents Hide How to Fix InvocationException: graphviz’s executables not found?On WindowsOn LinuxOn macOS Graphviz is open source graph visualization software that helps represent structural information as diagrams of…
View Post
Python - List Files In A Directory

Python – List Files in a Directory

Table of Contents Hide Method 1: Using os.listdir() methodMethod 2: Using os.walk() methodMethod 3: Using os.scan() methodMethod 4: Using glob module There are several modules available in Python to list…
View Post