Boolean Expressions

Boolean Expressions

What are Boolean expressions?

  • Boolean expressions are logical statements that can either be True or False.
  • These expressions are the basis of decision making in programming.

How to use Boolean expressions?

  • Boolean expressions are used in conditional statements, particularly if statements.
  • They include comparison operators such as == (equal to), != (not equal to), > (greater than), < (less than), >= (greater than or equal to), <= (less than or equal to).
  • They are also used in controlling loops such as while and for loops.

Manipulating Boolean expressions

  • Logical operators like AND, OR, and NOT can manipulate Boolean expressions.
  • If you have expression1 AND expression2, both must be true for the overall expression to be true.
  • If you have expression1 OR expression2, only one must be true for the overall expression to be true.
  • NOT expression inverts the truth value of the expression.

Short-circuiting

  • Short-circuiting is an important concept in Boolean expressions.
  • This happens when the truth value of the entire expression can be determined by just evaluating the first part of the expression.
  • For AND, the whole thing is false if the first part is false.
  • For OR, the whole thing is true if the first part is true.

Truth Tables

  • Truth tables are a useful tool to express the result of all possible combinations in a Boolean expression.
  • These express the output for all combinations of true and false for the different variables in the expression.

If Statements

What are If Statements?

  • If statements are control structures in programming that make decisions based on a Boolean expression’s outcome.

Usage of If Statements

  • If statement evaluates the Boolean expression within its brackets.
  • If the Boolean expression is true, it will run the block of code inside the if statement.
  • If false, it will skip over the code block.

If-Else statements

  • If-Else statements extend the decision making of an if statement.
  • else provides alternate code that will run if the if condition is False.

If-Elif-Else statements

  • elif is short for “else if” and is used to check multiple expressions for True and execute a block of code as soon as one of the conditions satisfies.
  • if, elif (optional), and else are combined to create decision structures that can handle multiple outcomes.