What are the bool values in Python

Get to know bool value in Python

The bool type has two values:True and False. We often use bool type variable with if statement.

The standard values False and None, numeric zero of all types including float, long, and so on, empty sequences such as empty strings, tuples, and lists, and empty dictionaries are all false. Everything else is interpreted as true, including the special value True.

The following values are considered by the interpreter to mean false :

False None 0 "" () [] {}

Python accepted almost anything in a boolean context

  • 0 is false; all other numbers are true.
  • An empty string ("") is false, all other strings are true.
  • An empty list ([]) is false; all other lists are true.
  • An empty tuple (()) is false; all other tuples are true.
  • An empty dictionary ({}) is false; all other dictionaries are true.

We can use bool function to convert other data types to bool data types.


print bool('java2s.com') 
print bool(42) # from  w  ww .ja  v a 2  s .  c om
print bool('') 
print bool(0) 

a = 0 
if a:
   print "Here"
   
a = 2

if a:
   print "There"   
if []:
   print "empty."
  
if [1]:
   print "not empty."
  
if ():
   print "empty."
  
if (1):
   print "not empty."

if {}:
   print "empty."
  
if {1:0}:
   print "not empty."

The code above generates the following result.

In fact, True and False are just 0 and 1 that look different but act the same.


print True # from ww w  . j  a va2 s  . c o  m
print False 
print True == 1 
print False == 0 
print True + False + 42 

The code above generates the following result.

The following code is using bool values numerically.


foo = 42#  www.  j  a  v a  2s . com
bar = foo < 100
print bar
print bar + 100
print '%s' % bar
print '%d' % bar

The code above generates the following result.





















Home »
  Python »
    Data Types »




Data Types
String
String Format
Tuple
List
Set
Dictionary