< previous | Table of Contents | next > |
3.2 LOGICAL OPERATORS
Logical operators are tools that enable you to combine Boolean expressions. These expressions result in either True
or False
and play an essential role in the decision-making process in your code. The three logical operators in Python are and
, or
, and not
. The values upon which logical operators operate are called operands.
AND OPERATOR
The and
operator evaluates to True
only if both conditions (operands) on its sides are True
.
# If the person is a student and also has an ISEC card then the cinema discount will apply is_student = True has_ISEC_card = True if is_student and has_ISEC_card: print("Movie ticket discount applied!") else: print("Not eligible for Movie ticket discount.")
OR OPERATOR
The or operator evaluates to True
if at least one of the conditions (operands) on its sides is valid.
# In the popular video game FIFA you can buy a pack either using coins or FIFA points # If we have one and not the other, we can still buy a pack. has_enough_coins = True has_enough_points = False if has_enough_coins or has_enough_points: print(“You can buy a FIFA pack!”) else: print(“You need to earn more coins or purchase points.”)
NOT OPERATOR
not
is an operator that flips the truth value of the operand. If the operand is True, applying not will make it False, and vice versa.
has_sufficient_funds = True if not has_sufficient_funds: print(“There are not enough funds to make a payment!”) else: print(“The payment was executed successfully!”)
THE TRUTH TABLE FOR LOGICAL OPERATORS
A truth table lists all possible combinations of truth values (True
or False
) for given variables and shows the result of the expression for each combination. X
and Y
in this table indicate the operands, meaning the two sides, of an expression and their respective truth values. The table says, for example, if the value of X
is True
and the value of Y
is true, then in case of the AND
operator the value would equal True
.
Table. Truth Table for Python Logical Operators. geeksforgeeks.org
KEY THINGS TO REMEMBER
- Logical operators are used to combine Boolean expressions. The expressions are referred to as operands.
and
isTrue
if both operands areTrue
.or
evaluates toTrue
if at least one of the operands isTrue
.not
inverts the truth value of the operand. If the opreand isTrue
thennot
will make itFalse
and vice versa.- If you're struggling to evaluate logical operators, draw out a truth table for your program.
SELF-CONTROL EXERCISES
< previous | Table of Contents | next > |