⬅ Previous Topic
Comparison OperatorsNext Topic ⮕
Assignment and Compound Assignment⬅ Previous Topic
Comparison OperatorsNext Topic ⮕
Assignment and Compound AssignmentLogical 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
or &&
)OR
or ||
)NOT
or !
)The AND operator returns true
only if both conditions are true. If either one is false, the entire expression evaluates to false.
IF (temperature > 20 AND temperature < 30)
PRINT "Weather is pleasant"
ENDIF
Weather is pleasant
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.
What will happen if temperature = 15?
The condition temperature > 20
is false, so the whole AND condition becomes false, and the message won't be printed.
The OR operator returns true
if at least one condition is true. It only returns false if both conditions are false.
IF (user_is_admin OR user_is_moderator)
PRINT "Access granted to control panel"
ENDIF
Access granted to control panel
Even if one of the two flags is true (admin or moderator), access will be granted. It allows for more flexible permission checks.
If both user_is_admin
and user_is_moderator
are false, will access be granted?
No. In that case, the OR condition is false and the message won't be printed.
The NOT operator inverts the result of a condition. If a condition is true, NOT makes it false. If false, it becomes true.
IF (NOT user_is_banned)
PRINT "User can post comments"
ENDIF
User can post comments
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.
What if user_is_banned = true
?
Then NOT user_is_banned
becomes false, and the message won't be printed.
You can combine multiple logical operators to build complex conditions.
IF ((age >= 18 AND has_id) OR is_accompanied_by_adult)
PRINT "Entry allowed"
ENDIF
Entry allowed
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.
Always use parentheses when combining logical operators to ensure the correct order of evaluation, especially when mixing ANDs and ORs.
⬅ Previous Topic
Comparison OperatorsNext Topic ⮕
Assignment and Compound AssignmentYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.