The bool() function converts a value to Boolean (True or False) using the standard truth testing procedure.
The syntax of bool()
is:
bool([value])
1. bool() parameters
It’s not mandatory to pass a value to bool()
. If you do not pass a value, bool()
returns False
.
In general use, bool()
takes a single parameter value
.
2. Return Value from bool()
bool()
returns:
False
if the value is omitted or falseTrue
if the value is true
The following values are considered false in Python:
None
False
- Zero of any numeric type. For example,
0
,0.0
,0j
- Empty sequence. For example,
()
,[]
,''
. - Empty mapping. For example,
{}
- objects of Classes which has
__bool__()
or__len()__
method which returns0
orFalse
All other values except these values are considered true.
3. Example: How bool() works?
test = [] print(test,'is',bool(test)) test = [0] print(test,'is',bool(test)) test = 0.0 print(test,'is',bool(test)) test = None print(test,'is',bool(test)) test = True print(test,'is',bool(test)) test = 'Easy string' print(test,'is',bool(test))
Output
[] is False [0] is True 0.0 is False None is False True is True Easy string is True
Related posts:
Python Directory and Files Management
Python Modules
Python max()
Python Program to Solve Quadratic Equation
Python dir()
Python timestamp to datetime and vice-versa
Python type()
Python Program to Shuffle Deck of Cards
Python String ljust()
Python Program to Find All File with .txt Extension Present Inside a Directory
Python Global, Local and Nonlocal variables
Python String isspace()
Python Program to Concatenate Two Lists
Python Program to Get the Last Element of the List
Python Type Conversion and Type Casting
Python Data Analytics with Pandas, NumPy and Matplotlib - Fabio Nelli
Python memoryview()
Python Program to Check if a Number is Odd or Even
Python String strip()
Python pass statement
Python ord()
Python Program to Find the Factorial of a Number
Python Tuple index()
Python id()
Python time Module
Python Program to Get the Full Path of the Current Working Directory
Python Program to Get the Class Name of an Instance
Python Dictionary keys()
Python Matrices and NumPy Arrays
Python all()
Python @property decorator
Python Program to Get Line Count of a File