What Are Logical Operators?
Logical operators are used in programming to make decisions based on one or more conditions. These are typically used in conditional statements and loops to control the flow of a program.
The three primary logical operators are:
- AND (often written as
AND
or&&
) - OR (often written as
OR
or||
) - NOT (often written as
NOT
or!
)
1. Logical AND Operator
The AND operator returns true
only if both conditions are true. If either one is false, the entire expression evaluates to false.
Example:
IF (temperature > 20 AND temperature < 30)
PRINT "Weather is pleasant"
ENDIF
Output:
Weather is pleasant
Explanation:
This condition checks if the temperature is between 20 and 30. If both parts of the condition are true, only then the message is printed.
Question:
What will happen if temperature = 15?
Answer:
The condition temperature > 20
is false, so the whole AND condition becomes false, and the message won't be printed.
2. Logical OR Operator
The OR operator returns true
if at least one condition is true. It only returns false if both conditions are false.
Example:
IF (user_is_admin OR user_is_moderator)
PRINT "Access granted to control panel"
ENDIF
Output:
Access granted to control panel
Explanation:
Even if one of the two flags is true (admin or moderator), access will be granted. It allows for more flexible permission checks.
Question:
If both user_is_admin
and user_is_moderator
are false, will access be granted?
Answer:
No. In that case, the OR condition is false and the message won't be printed.
3. Logical NOT Operator
The NOT operator inverts the result of a condition. If a condition is true, NOT makes it false. If false, it becomes true.
Example:
IF (NOT user_is_banned)
PRINT "User can post comments"
ENDIF
Output:
User can post comments
Explanation:
This check ensures that only users who are not banned can post. It's a common use-case for the NOT operator to guard against restricted access.
Question:
What if user_is_banned = true
?
Answer:
Then NOT user_is_banned
becomes false, and the message won't be printed.
Combining Logical Operators
You can combine multiple logical operators to build complex conditions.
Example:
IF ((age >= 18 AND has_id) OR is_accompanied_by_adult)
PRINT "Entry allowed"
ENDIF
Output:
Entry allowed
Explanation:
This condition checks if the person is at least 18 and has an ID, or is with an adult. If either path to validation is satisfied, access is granted.
Tip for Beginners:
Always use parentheses when combining logical operators to ensure the correct order of evaluation, especially when mixing ANDs and ORs.