2 3 3 Logical Operators Explained
Key Concepts
2 3 3 Logical Operators in Python refer to the three primary logical operators used to combine and manipulate boolean values: and
, or
, and not
. These operators are essential for controlling the flow of programs through conditional statements.
1. Logical AND (and
)
The and
operator returns True
if both operands are True
. If either operand is False
, the result is False
.
a = True b = False result = a and b # Output: False
Think of the and
operator as a series of switches that must all be "on" for the result to be "on."
2. Logical OR (or
)
The or
operator returns True
if at least one of the operands is True
. If both operands are False
, the result is False
.
a = True b = False result = a or b # Output: True
Think of the or
operator as a series of switches where at least one must be "on" for the result to be "on."
3. Logical NOT (not
)
The not
operator returns the opposite boolean value of its operand. If the operand is True
, not
returns False
, and vice versa.
a = True result = not a # Output: False
Think of the not
operator as a switch that flips the state of a boolean value.
Combining Logical Operators
Logical operators can be combined to create more complex conditions. For example, you can use and
and or
together to check multiple conditions.
a = True b = False c = True result = (a and b) or c # Output: True
In this example, the expression (a and b)
evaluates to False
, but since c
is True
, the entire expression evaluates to True
.
Practical Example: Conditional Statements
Logical operators are commonly used in conditional statements to control the flow of a program. For example:
age = 25 is_student = True if age < 30 and is_student: print("You qualify for a student discount.") else: print("You do not qualify for a student discount.")
In this example, the program checks if the person is both under 30 years old and a student to determine if they qualify for a discount.