Built-in bool() function

You can check if a value is either truthy or falsy with the built-in bool() function. This function is used to return or convert a value to a Boolean value i.e., True or False, using the standard truth testing procedure

Syntax: bool(parameter)

You only need to pass the value as an argument.

Example:

Python3




bool(7)
# True
  
bool(0)
 #False
    
bool([])
# False
  
bool({7,4})
#True
  
bool(-4)
# True
  
bool(0.0)
# False
  
bool(None)
# False
  
bool(1)
#True
  
bool(range(0))
# False
  
bool(set())
# False
  
bool([1,2,3,4])
# True


Output:

True
False
False
True
True
False
False
True
False
False
True

Now let’s see a program for better understanding of Truthy and Falsy value.

Example:

Python3




# define a function for checking
# number is even or odd
def even_odd(number):
    
  if number % 2
      
     # since num % 2 is equal to 1
     # which is Truthy Value
     return 'odd number'
      
  else
      
     # since num%2 is equal to 0
     # which is Falsy Value.
     return 'even number'
  
result1 = even_odd(7)
  
# prints odd
print(result1) 
  
result2 = even_odd(4)
  
# prints even
print(result2) 


Output:

odd number
even number

Since in first function call num % 2 is equal to 1 which is Truthy Value, so output is ‘odd number’ and in second function call num % 2 is equal to 0 which Falsy Value, so output is ‘even number’.



Truthy vs Falsy Values in Python

In this article, we will see about the concept of Truthy and Falsy values in Python and also see how to determine a value is Truthy or Falsy by using bool() built-in Python function.

Now, Let’s start with the following two codes:

Python3




number = 7
if number:
  print(number)


Output:

7

Let’s change value of number to 0

Python3




number = 0
if number:
  print(number)


Output:

There is no Output

Have you wondered why the above code run successfully despite number not being an expression?

The answer lies in concept of Truthy and Falsy Values.

Similar Reads

Truthy vs Falsy Values

...

Built-in bool() function

...

Contact Us