DEV Community

Srinivas Ramakrishna for ItsMyCode

Posted on • Originally published at itsmycode.com on

Python bool()

ItsMyCode |

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])**
Enter fullscreen mode Exit fullscreen mode

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))

Enter fullscreen mode Exit fullscreen mode


python

Output

False is False
True is True
() is False
{} is False
0.0 is False
None is False
ItsMyCode is True
Enter fullscreen mode Exit fullscreen mode

The post Python bool() appeared first on ItsMyCode.

Top comments (0)