Logical Operators

Logical operators combine or invert boolean conditions. They are used to build compound conditions — checks that require more than one thing to be true at the same time, or where either of two things being true is enough.

For a broader introduction to operators, see Operators.

AND#

The AND operator returns true only when both conditions are true. If either is false, the result is false.

Left Right Result
true true true
true false false
false true false
false false false
int score = 7;
bool result = score > 5 && score < 10;  // true
score = 7
result = score > 5 and score < 10  # True
let score = 7;
let result = score > 5 && score < 10;  // true

OR#

The OR operator returns true when at least one condition is true. It only returns false when both are false.

Left Right Result
true true true
true false true
false true true
false false false
int score = 3;
bool result = score < 2 || score > 5;  // false
score = 3
result = score < 2 or score > 5  # False
let score = 3;
let result = score < 2 || score > 5;  // false

NOT#

The NOT operator inverts a boolean. true becomes false and false becomes true.

bool isEven = 4 % 2 == 0;   // true
bool isOdd  = !isEven;       // false
is_even = 4 % 2 == 0  # True
is_odd  = not is_even  # False
let isEven = 4 % 2 === 0;  // true
let isOdd  = !isEven;       // false

Common Mistakes#

Confusing && with || && requires both conditions to be true. || requires only one. Swapping them produces logically opposite behaviour — a loop or condition that should stop keeps going, or one that should continue stops early.

Repeating the variable name unnecessarily Writing score > 5 && > 10 is a syntax error. Each comparison must be complete: score > 5 && score < 10.

Short-circuit evaluation surprises In most languages, && stops evaluating as soon as the first condition is false, and || stops as soon as the first is true. This matters when the second condition has a side effect — it may not run at all.

Using and/or syntax in C# or JavaScript C# and JavaScript use && and ||. Writing and or or in those languages causes a compile or syntax error. Python uses and, or, and not as keywords instead of symbols.

Resources#