What are other boolean conversions?

In Python, several types of values can be converted to boolean using the bool() function. Here are some common conversions:

  1. Numbers:

    • Non-zero numbers (e.g., 1, -1, 3.14) are True.
    • Zero (0, 0.0) is False.
  2. Strings:

    • Non-empty strings (e.g., "Hello", " " (space)) are True.
    • Empty strings ("") are False.
  3. Lists, Tuples, Sets, and Dictionaries:

    • Non-empty collections (e.g., [1, 2], (1,), {1}, {'key': 'value'}) are True.
    • Empty collections ([], (), set(), {}) are False.
  4. None:

    • The value None is False.
  5. Custom Objects:

    • By default, instances of user-defined classes are True, unless the class defines a __bool__() or __len__() method that returns False or 0.

Here are some examples:

print(bool(42))            # True
print(bool(0))             # False
print(bool("Python"))      # True
print(bool(""))            # False
print(bool([1, 2, 3]))     # True
print(bool([]))            # False
print(bool(None))          # False

These conversions are useful for controlling flow in conditional statements and loops. If you have more questions or need further examples, let me know!

0 Comments

no data
Be the first to share your comment!