ython Booleans – True and False


Python Boolean Data Type

In Python, the Boolean data type is used to represent one of two values:

  • True
  • False

Booleans are mainly used in conditional statements, comparisons, and loops to control program flow.

1. Boolean Type

Python has a built-in type called bool, which can hold one of two values: True or False.

Example:

a = True
b = False

print(type(a))
print(type(b))

Output:

<class 'bool'>
<class 'bool'>

2. Booleans from Comparison Operators

Python expressions that use comparison operators return Boolean values.

Example:

x = 10
y = 5

print(x > y)    # True
print(x == y)   # False
print(x != y)   # True
print(x <= 10)  # True

Output:

True
False
True
True

3. Booleans in if Statements

Booleans are most often used in conditional logic with if, elif, and else.

Example:

is_logged_in = True

if is_logged_in:
    print("Welcome back!")
else:
    print("Please log in.")

Output:

Welcome back!

4. The bool() Function

The bool() function can convert any value to a Boolean:

Truthy and Falsy Values

  • Falsy values: 0, None, False, '' (empty string), [], {}, set()
  • Truthy values: Any non-zero or non-empty value

Example:

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

Output:

False
True
False
True
False
True

5. Boolean Operators: and, or, not

and - Both conditions must be True

a = 5
b = 10

print(a > 2 and b < 15)  # True and True = True
print(a > 6 and b < 15)  # False and True = False

or - At least one condition is True

print(a > 2 or b > 20)   # True or False = True
print(a > 6 or b > 20)   # False or False = False

not - Invert the Boolean

print(not True)          # False
print(not False)         # True

6. Boolean in Loops

Booleans are often used in while loops.

count = 0
while count < 3:
    print("Counting:", count)
    count += 1

Output:

Counting: 0
Counting: 1
Counting: 2

Summary of Python Boolean Concepts

Concept Example Result Boolean literal True, False bool type Comparison 5 > 3 True Logical AND True and False False Logical OR True or False True Logical NOT not True False Conversion to bool bool([]) False