bool () in Python

Python Methods and Functions

The bool () method is used to return or convert a value to a Boolean value, that is, True or False, using the standard truth test. 
Syntax :

  bool ([x])  

In general, the bool () method accepts only one parameter (here x) to which the standard plausibility check can be applied.  If the parameter is not passed, then False is returned by default . Thus, passing the parameter is optional. It can return one of two values.

  • Returns True if the passed parameter or value — True.
  • It returns False if the passed parameter or value is False.

Here are some cases where Python's bool () method returns false. Apart from these, all other values ​​return True.

  • If a false value is passed.
  • If None is passed.
  • If an empty sequence is passed, for example (), [], ”, Etc.
  • If Zero is passed in any numeric type such as 0, 0.0, etc.
  • If empty match is omitted, for example {}.
  • If class objects have a __bool __ () or __len () __ method, returning 0 or False

# Python program for illustration
# built-in bool () method

 
# Returns False because x is False

x = False

print ( b ool (x))

 
# Returns True because x is True

x = True

print ( bool (x))

  
# Returns False because x is not equal to y

x = 5

y = 10

print ( bool (x = = y))

 
# Returns False because x is None

x = None

print ( bool (x))

 
# Returns False because x is an empty string

x = ()

print ( bool (x))

 
# Returns False because x is a blank display

x = {}

print ( bool (x))

 
# Returns False because x is 0

x = 0.0

print ( bool (x))

  
# Returns True because x is not an empty string

x = 'GeeksforGeeks'

print ( bool (x))

Output:

 False True False False False False False True 

application

Here is a program to find out even and odd using the bool () method. You can use other inputs and check the results. 
Example:

# Python code to check for number availability
# is even or odd with bool ()

 

def check (num):

return ( bool (num % 2 = = 0 ))

  
Driver code

num = 8

if (check (num)):

print ( "Even" )

else :

print ( "Odd" )

Exit:

 Even 




Tutorials