Booleans

What Are Booleans?

  • Booleans represent one of two values: True or False.

Boolean Values:

  • In programming, you often need to know if an expression is true or false.
  • Python allows you to evaluate any expression and get True or False.

Comparing Values:

  • When you compare two values, Python returns a Boolean answer.

    python
    print(10 > 9)   
    print(10 == 9)  
    print(10 < 9)  
    • Output: True
    • Output: False
    • Output: False

Evaluate Values and Variables:

  • The bool() function allows you to evaluate any value and return True or False.

    python
    print(bool("Hello"))  
    print(bool(15))  
    • Output: True
    • Output: True
  • Evaluating variables:

    python
    x = "Hello"
    y = 15
    
    print(bool(x))  
    print(bool(y))  
    • Output: True
    • Output: True

Most Values Are True:

  • Almost any value is evaluated to True if it has some sort of content.

    • Any string is True, except empty strings.
    • Any number is True, except 0.
    • Any list, tuple, set, and dictionary are True, except empty ones.
    python
    print(bool("abc"))  
    print(bool(123)) 
    print(bool(["apple", "cherry", "banana"]))  
    • Output: True
    • Output: True
    • Output: True

Some Values Are False:

  • Empty values, such as (), [], {}, "", the number 0, and the value None evaluate to False. The value False also evaluates to False.

    python
    print(bool(False))  
    print(bool(None))  
    print(bool(0))  
    print(bool(""))  
    print(bool(()))  
    print(bool([]))  
    print(bool({}))  
    • Output: False
    • Output: False
    • Output: False
    • Output: False
    • Output: False
    • Output: False
    • Output: False
  • Booleans are fundamental in programming for evaluating expressions and controlling the flow of code with conditions. Practice using Boolean values, the bool() function, and conditions to understand their importance in Python!