Logical Operators

Logical Operators return boolean result which makes them suitable for if statements.

Operator Description Examples Result
! Not - inverse the value. !true false
!false true
!(2 + 3 == 5) false
&& And
  • true if all statements are true.
  • false - if one or more statements are false.
true && true && true true
false && false && false false
true && false false
|| Or
  • true if one or more statements are true.
  • false - if all statements are false.
true || true || true true
false || false || false false
true || false true

Example

Let's look at the following example. Depending on a test score, determine whether the score is low, medium, high or invalid following these rules:

  • 0 to 50 - low
  • 51 to 75 - medium
  • 76 to 100 - high
  • less than 0 or more than 100 - invalid

Output:

Explanation:

  • To check whether a number is between 2 values && (AND) operator can be used.
  • Line 4 checks whether number is greater or equal to 0 and if it's less or equal to 50.
  • Line 16 checks whether number is less than 0 or if it's greater than 100.