A Boolean is a type of data that can have one of two possible values:

  • True
  • False

These are the only two possible Boolean values. Think of them like yes (True) or no (False) answers.

Why are Booleans important?

Booleans are used in Python for decisions and conditions. For example, we can use Booleans to check if something is true or false, like:

  • “Is the number 5 greater than 3?” (True)
  • “Is 2 equal to 5?” (False)

How to Create Booleans in Python

In Python, you can use the words True and False directly to represent Boolean values.

Example 1: Simple Boolean Values

is_happy = True
is_sad = False

print(is_happy)  # This will print: True
print(is_sad)    # This will print: False

In the example above:

  • is_happy is set to True.
  • is_sad is set to False.

Boolean Operations

Just like in real life, where we can combine “yes” and “no” answers, we can combine Booleans using special operators.

Example 2: and, or, and not Operations

  • and: This means both conditions must be True for the result to be True.
  • or: This means at least one condition must be True for the result to be True.
  • not: This reverses the Boolean value. If something is True, not makes it False, and vice versa.

Using and

is_raining = True
has_umbrella = False

can_go_out = is_raining and has_umbrella
print(can_go_out)  # This will print: False because both need to be True for "and"

Using or

is_raining = True
has_umbrella = False

can_go_out = is_raining or has_umbrella
print(can_go_out)  # This will print: True because only one needs to be True for "or"

Using not

is_raining = True
not_raining = not is_raining
print(not_raining)  # This will print: False because it is the opposite of True

Boolean Comparison Operators

Python allows you to compare values using Boolean results. Common comparisons are:

  • ==: Is equal to?
  • !=: Is not equal to?
  • >: Greater than?
  • <: Less than?
  • >=: Greater than or equal to?
  • <=: Less than or equal to?

Example 3: Boolean Comparisons

x = 10
y = 20

print(x == y)  # False, because 10 is not equal to 20
print(x != y)  # True, because 10 is not equal to 20
print(x < y)   # True, because 10 is less than 20
print(x > y)   # False, because 10 is not greater than 20

Combining Multiple Conditions

You can combine these comparisons with and/or operators.

Example 4: Complex Conditions

x = 10
y = 20
z = 30

result = x < y and z > y
print(result)  # This will print: True because both comparisons are True

if Statements and Booleans

Booleans are often used with if statements to make decisions in Python. An if statement checks if a condition is True, and if it is, it will run some code.

Example 5: Using Booleans in if Statements

is_raining = True

if is_raining:
    print("Take an umbrella!")
else:
    print("Enjoy the sunshine!")

In this example:

  • If is_raining is True, it will print "Take an umbrella!".
  • If is_raining is False, it will print "Enjoy the sunshine!".