Python Logical Operators
Logical Operators in Python
Logical operators in Python are used to combine conditional statements and evaluate logical expressions. They allow you to perform logical operations on Boolean values (True
and False
) and are commonly used in control flow statements, such as if
statements, to determine the outcome based on multiple conditions.
List of Logical Operators
Operator | Description | Example | Output |
---|---|---|---|
and | Returns True if both operands are true | a and b | Depends on a and b |
or | Returns True if at least one operand is true | a or b | Depends on a and b |
not | Returns True if the operand is false (negates the Boolean value) | not a | Depends on a |
Examples of Logical Operators
1. Logical AND (and
)
The and
operator returns True
if both operands are true; otherwise, it returns False
.
2. Logical OR (or
)
The or
operator returns True
if at least one of the operands is true. If both are false, it returns False
.
3. Logical NOT (not
)
The not
operator negates the Boolean value of its operand. If the operand is True
, it returns False
, and vice versa.
Using Logical Operators in Conditional Statements
Logical operators are often used in if
statements to combine multiple conditions.
Example with Multiple Conditions
You can combine multiple logical conditions using and
, or
, and not
.
Short-circuit Evaluation
Logical operators in Python use short-circuit evaluation, meaning:
- For
and
, if the first operand isFalse
, the second operand is not evaluated because the overall result cannot beTrue
. - For
or
, if the first operand isTrue
, the second operand is not evaluated because the overall result will beTrue
.
Example:
Summary of Logical Operators:
and
: ReturnsTrue
if both operands are true; otherwise returnsFalse
.or
: ReturnsTrue
if at least one operand is true; returnsFalse
only if both are false.not
: Negates the Boolean value of the operand; returnsTrue
if false, andFalse
if true.
Logical operators are essential for controlling the flow of logic in Python programs, enabling complex conditions and decision-making processes.