How To Use Python bool() Function To Convert Variable To Boolean Examples

The bool() function in Python is used to convert a value to a Boolean (True or False) value. In this article, I will show you some examples on how to use the bool() function.

1. Python bool() Function Examples.

1.1 Example 1.

  1. Using bool() with integers.
    >>> print(bool(0))
    False
    >>> print(bool(1))
    True
    >>> print(bool(-1))
    True
    >>>
    >>> print(bool(10))
    True
    >>> print(bool(-10))
    True
  2. In this example, bool() is used to convert integers to Boolean values. Any non-zero integer will be converted to True, while zero will be converted to False.

1.2 Example 2.

  1. Using bool() with strings.
    >>> print(bool(""))
    False
    >>> print(bool(" "))
    True
    >>> print(bool("hello"))
    True
  2. In this example, bool() is used to convert strings to Boolean values. An empty string will be converted to False, while any non-empty string will be converted to True.

1.3 Example 3.

  1. Using bool() with lists.
    >>> print(bool([]))
    False
    >>>
    >>> print(bool([1,2,3]))
    True
  2. In this example, bool() is used to convert lists to Boolean values. An empty list will be converted to False, while any non-empty list will be converted to True.

1.4 Example 4.

  1. Using bool() with None.
    >>> print(bool(None))
    False
  2. In this example, bool() is used to convert None to a Boolean value. None will be converted to False.

1.5 Example 5.

  1. Using bool() with functions.
    >>> def foo():
    ...     return 1
    ...
    >>> def bar():
    ...     return None
    ...
    >>> print(bool(foo()))
    True
    >>> print(bool(bar()))
    False
  2. In this example, bool() is used to convert functions to Boolean values.
  3. Any function will be converted to True, regardless of its return value.
  4. Note: In Python, several values are considered “falsey” and will be converted to False by bool().
  5. These include False, 0, None, empty sequences (e.g., "", [], ()), and empty mappings (e.g., {}).
  6. All other values are considered “truthy” and will be converted to True.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.