A Boolean is a built-in data type in Python used to represent truth values. It can have only two possible values: True and False. These values are fundamental for making decisions and controlling the flow of a program.
Boolean Values in Python
In Python, True and False are reserved keywords that represent Boolean truth values. They must be written with an uppercase first letter; lowercase true or false are not Boolean values.
Boolean from Comparisons
Booleans often result from comparison expressions, which evaluate two values or variables.
Here, x > y is True because 10 is greater than 5. x == y is False because 10 is not equal to 5.
Boolean in Conditional Logic
Booleans are used in conditional statements to control program flow:
Python executes the appropriate block based on whether the Boolean expression is True or False.
Truthiness and Falsiness
Python uses the concept of truthiness and falsiness to evaluate non-Boolean values in Boolean contexts:
-
Truthy values: Non-zero numbers, non-empty strings, lists, or other containers are considered
True. -
Falsy values: Zero (
0,0.0), empty strings"",None, and empty collections (like[],{},()) are consideredFalse.
You can explicitly convert a value to a Boolean usingbool().
Boolean Operations
Python supports boolean operators to combine or modify Boolean expressions:
-
and- True if both expressions are True -
or- True if at least one expression is True -
not- Inverts the Boolean value
These operators are often used in conditions involving multiple checks.
Boolean in Python Logic
Booleans are essential in loops, conditionals, and expressions where decisions are required. They enable code to evaluate conditions and act accordingly - for example, checking user input, comparing values, or validating states