The value of the bool function in python

  • 2021-01-18 06:34:27
  • OfStack

bool is short for Boolean, and there are only two values for true (True) and false (False)

The bool function takes only one argument and returns true or false based on the value of that argument.

1. When using the bool function on a number, 0 returns false (False), and any other value returns true.


>>> bool(0)
False
>>> bool(1)
True
>>> bool(-1)
True
>>> bool(21334)
True

2. When using bool on a string, it returns False for a string with no value (that is, None or an empty string), otherwise it returns True.


>>> bool('')
False
>>> bool(None)
False
>>> bool('asd')
True
>>> bool('hello')
True

3. The bool function returns False for empty lists, dictionaries, and primitives, or True otherwise.


>>> a = []
>>> bool(a)
False
>>> a.append(1)
>>> bool(a)
True

4. Use the bool function to determine if a value has been set.


>>> x = raw_input('Please enter a number :')
Please enter a number :
>>> bool(x.strip())
False
>>> x = raw_input('Please enter a number :')
Please enter a number :4
>>> bool(x.strip())
True

Related articles: