Geek Slack

Introduction to Python
    About Lesson



    Python Booleans


    Python Booleans

    Booleans in Python represent the truth values True and False.

    1. Boolean Values

    Python has two built-in boolean values: True and False.

    Example:

    x = True
    y = False

    2. Boolean Operations

    Python supports various boolean operations, including and, or, and not.

    Example:

    a = True
    b = False
    
    result_and = a and b      # False
    result_or = a or b        # True
    result_not = not a        # False

    3. Comparison Operators

    Comparison operators in Python return boolean values based on the comparison of two operands.

    Example:

    x = 5
    y = 10
    
    result_equal = x == y        # False
    result_not_equal = x != y    # True
    result_greater = x > y       # False
    result_less = x < y          # True
    result_greater_equal = x >= y    # False
    result_less_equal = x <= y       # True

    4. Boolean Conversion

    Many values in Python can be evaluated as boolean expressions. For example, any non-zero number or non-empty container is considered True.

    Example:

    x = 0
    y = 10
    z = []
    
    result_x = bool(x)      # False
    result_y = bool(y)      # True
    result_z = bool(z)      # False

    Conclusion

    Booleans are essential in Python for making decisions and controlling the flow of programs. Understanding boolean operations and comparison operators is crucial for writing effective Python code.