Python Booleans

About Python Booleans

In Python, booleans are a data type that represents either True or False.

  • True represents the true condition.
  • False represents the false condition.

Booleans are essential for decision-making processes in conditional statements, loop structures, and functions.

Get Booleans from Comparison

You can get Boolean result from comparison using the following comparison operators:

  • '==' (equal to)
  • '!=' (not equal to)
  • '<' (less than)
  • '>' (greater than)
  • '<=' (less than or equal to)
  • '>=' (greater than or equal to)

In the following example, 'x = 10' and 'y = 20'. The first comparison 'x > y' is not true as x is not greater than y. The second comparison 'x == y' is not true as x and y are not equal. The third comparison is true as x and y are not equal.

Please have a closer look at the following examples:

Example of Comparison:
Output of the above example
False
False
True
                                

Booleans in control flow statements

Boolean expressions are commonly used in control flow statements like 'if', 'elif', and 'else'.

In the following example, the x and y variables are used in the control flow statements- 'if', 'elif', and 'else'. As the 'if' and 'elif' statements are false, it falls back to the 'else' statement and prints "x is not greater than y."

Please have a closer look at the following examples:

Example of Boolean expressions in control flow statements:
Output of the above example
x is not greater than y.
                                

Boolean operations in Python

Python supports several boolean operations, including 'and', 'or', and 'not'.

The 'and' operator returns True if both operands are true; otherwise, it returns False.

The 'or' operator returns True if at least one of the operands is true; otherwise, it returns False.

The 'not' operator returns the opposite boolean value of its operand.

Please have a closer look at the following examples:

Example of Boolean operations:
Output of the above example
False
True
True
                                

Boolean conversion in Python

In Python, other data types or values can be converted into Boolean values (True or False) using 'bool()' function.

Values include False, None, 0, empty sequences (like '' or []), and empty mappings (like {}) return False.

All other values return True.

Please have a closer look at the following examples:

Example of Boolean conversion:
Output of the above example
True
False
True
False
                                

Python Compiler For Live Practice

Practice the above Python code in the following Python Editor. Create more Python boolean variables and perform boolean conversion in the following Python code editor and click Execute button. Output will be displayed in Python Code Output section.

Python logo Python Editor
Python Code Output