Logical Operators (and, or, not) in Python
Logical operators are used to combine two or more conditions in a program. Logical operators are essential for creating more complex programs and for decision making. In Python, the logical operators are and
, or
, and not
. They are used to evaluate two or more conditions and decide the output.
AND Operator
The and
operator evaluates two conditions and returns True
if both conditions are True
. It will return False
if one or both of the conditions are False
. Here is an example:
a = 5 b = 6 if (a > 3) and (b > 3): print("Both conditions are true")
In the example above, both a > 3
and b > 3
are True
, so the print
statement will be executed.
OR Operator
The or
operator evaluates two conditions and returns True
if either condition is True
. It will return False
only if both conditions are False
. Here is an example:
a = 5 b = 2 if (a > 3) or (b > 3): print("At least one condition is true")
In this example, a > 3
is True
so the print
statement will be executed.
NOT Operator
The not
operator is used to reverse the logical state of a condition. It will take a condition that is True
and evaluate it to False
, and vice versa. Here is an example:
a = 5 if not a == 3: print("a is not equal to 3")
In this example, a
is not equal to 3, so the print
statement will be executed.
Tips
- The
and
andor
operators can be used to combine multiple conditions. - The
not
operator can be used to reverse the logical state of a condition. - Logical operators are important for decision making in a program.