Python Logical Operators - Introduction
Logical operators in Python are used to perform logical operations on variables and expressions. They return either True
or False
depending on the condition of the operands. Python has three logical operators: and
, or
, and not
.
Here’s a breakdown of how each works:
1. and
Operator
The and
operator returns True
if both the operands (conditions) are true. If either or both of the operands are false, the result is False
.
In this example, since a
is True
and b
is False
, the result of a and b
is False
.
2. or
Operator
The or
operator returns True
if at least one of the operands is true. If both are false, the result is False
.
Here, a
is True
and b
is False
, but since at least one operand (a
) is true, the result of a or b
is True
.
3. not
Operator
The not
operator is a unary operator that inverts the Boolean value of the operand. It returns True
if the operand is false, and False
if the operand is true.
In this case, since a
is True
, the not
operator inverts it and the result becomes False
.
Precedence of Logical Operators
The precedence of logical operators determines the order in which they are evaluated in a complex expression. The precedence in Python is as follows:
not
and
or
You can use parentheses to group expressions and control the evaluation order.
Use Cases
Logical operators are widely used in:
- Conditional statements: To make decisions based on multiple conditions.
- Loops: To continue or break loops based on compound conditions.
- Filtering data: To select elements based on specific logical conditions in lists, dictionaries, etc.
Logical operators in Python make it easy to build complex decision-making conditions in your code.