If you're seeing this message, it means we're having trouble loading external resources on our website.

If you're behind a web filter, please make sure that the domains *.kastatic.org and *.kasandbox.org are unblocked.

### Course: AP®︎/College Computer Science Principles>Unit 3

Lesson 5: Conditionals

# Compound Booleans with logical operators

We can implement any logic in a program using only nested conditionals. However, we can make shorter and more expressive code by combining simple Boolean expressions using logical operators (and, or, not) to create compound Boolean expressions.

## The OR operator

Using the OR operator, we can create a compound expression that is true when either of two conditions are true.
Imagine a program that determines whether a student is eligible to enroll in AP CS A. The school's requirement is that the student must either have earned at least 75% in AP CSP or in Intro to programming.
One way to implement that logic is with two separate `if` statements, like in the JavaScript code below:
``````if (cspGrade >= 75) {
println("You're eligible for AP CS A!");
}
println("You're eligible for AP CS A");
}``````
That code is problematic, however: we've repeated the same instructions in 2 places, and that means we now have to update 2 places whenever we want to change the instructions. It's very likely for one to get out of sync with the other; in fact, it's already the case! Can you spot the slight difference in the two `println()`s?
A much better approach is to use an OR operator to combine those two conditions.
In JavaScript, the OR operator is represented by two vertical pipes, `||`, nestled between two conditions:
``````if (cspGrade >= 75 || progGrade >= 75) {
println("You're eligible for AP CS A!");
}``````
📝 See similar code in: App Lab | Snap | Python
Our new code implements the same logic, but is much shorter and easier to maintain.
If the school adds a third way to be eligible, like completing a summer camp, we can easily add that to the compound expression using an additional OR operator and condition:
``````if (cspGrade >= 75 ||
summerCamp === true) {
println("You're eligible for AP CS A!");
}``````
📝 See similar code in: App Lab | Snap | Python
Since that expression is made entirely of OR operators, the expression is true as long as any of the conditions are true. It will only be false if every single condition is false.
Consider this snippet of JavaScript:
``````if (temperature < 40 || weather === "rain") {
println("Wear a jacket!");
}``````
📝 See similar code in: App Lab | Snap | Python
In which situations will this code display the warning to wear a jacket?

## The AND operator

Using the AND operator, we can create a compound expression that is true only when both of the conditions are true.
Let's make a program that determines whether a student meets a university's graduation requirements. The university requires that the student has a cumulative GPA higher than 2.0 and that the student has completed at least 120 units.
One way to implement that logic is with nested conditionals:
``````if (cumulativeGPA > 2.0) {
if (totalUnits >= 120) {
}
}``````
We can shorten that code significantly by using an AND operator however.
In JavaScript, the AND operator is represented by two ampersands, `&&`, placed between the two conditions:
``````if (cumulativeGPA > 2.0 &&  totalUnits >= 120) {
}``````
📝 See similar code in: App Lab | Snap | Python
This code is logically equivalent to the nested conditional, but it's both shorter and easier to read; a win-win!
If graduation requirements become stricter, we can expand that expression with more `&&` operators:
``````if (cumulativeGPA > 2.0 &&
totalUnits >= 120 &&
languageUnits >= 8) {
}``````
📝 See similar code in: App Lab | Snap | Python
Since that compound expression is made entirely out of AND operators, every condition must be true for the computer to execute the instructions inside. As soon as any of those expressions are false, the entire expression is false.
Consider this snippet of JavaScript:
``````if (weather === "rain" && transportMode === "walking") {
println("Take an umbrella!");
}``````
📝 See similar code in: App Lab | Snap | Python
In which situations will this code display the warning to take an umbrella?

## The NOT operator

Using the NOT operator, we can reverse the truth value of an entire expression, from true to false or false to true.
Imagine a university wants to send a warning only to those students who are not eligible for graduation.
There are a few ways to implement that logic with nested conditionals.
One way is to create a `if/else` conditional using the previous condition for graduation eligibility and not put any instructions inside the `if` block:
``````if (cumulativeGPA > 2.0 &&  totalUnits >= 120) {
// Do nothing
} else {
sendEmail();
}``````
That code is a bit awkward and unnecessarily long, so we'd really like to avoid writing code like that.
Another way is to figure out how to express logically that a student has not met the requirements, like so:
``````if (cumulativeGPA <= 2.0 ||  totalUnits < 120) {
sendEmail();
}``````
That approach is much better; it's shorter and readable: "If the cumulative GPA is less than or equal to 2.0 or the units completed are less than 120, then send the email."
The NOT operator gives us a third way, however: we can "NOT" the entire original expression.
In JavaScript, the NOT operator is represented by a single exclamation point, `!`, and needs to be placed in front of the expression to negate:
``````if (!(cumulativeGPA > 2.0 &&  unitsCompleted >= 120)) {
sendEmail();
} ``````
📝 See similar code in: App Lab | Snap | Python
The code above uses parentheses to make sure the NOT is applied to the entire compound expression, and not just to one of the conditions. This code can be read as "if it's not the case that the cumulative GPA is greater than 2.0 and the units completed are at least 120, then send the email."
It's up to you which of the two good approaches you use; both are logically equivalent. You could decide to never use NOT in your own expressions, but you will certainly run into it in the programs of others, so it's important to be able to understand it.
Consider this code snippet:
``````if (!(temperature < 70 || weather === "rain")) {
println("Gardening day!");
}``````
📝 See similar code in: App Lab | Snap | Python
In which situations will this code declare that it's a gardening day?

## All together now

We can combine the AND/OR/NOT operators in our conditionals to implement more complex logic.
Imagine a high school that requires their students to pass Biology and pass either Chemistry or Physics. We can write a program that checks for that in a single compound expression:
``````if (biologyGrade > 65 &&
println("science requirement satisfied");
}``````
📝 See similar code in: App Lab | Snap | Python
Notice the use of parentheses around the OR expression. Just like arithmetic operators, logical operators have an order of operations: first NOT, then AND, then OR. If we had left out the parentheses above, the computer would AND the first two conditions, and then OR the result of that with the final condition; a logically different expression. Always use parentheses to make sure the computer evaluates the conditions in the expected order.
We can also NOT that entire expression:
``````if (!(biologyGrade > 65 &&
println("science requirement NOT satisfied");
}``````
📝 See similar code in: App Lab | Snap | Python
Compound expressions can be intimidating when you first look at them, especially if you're new to programming and still learning the various operators.
You may find it helpful to translate the expression into written speech. For example, we can write the above as "If it is not the case that the biology grade is passing and that either the chemistry grade is passing or the physics grade is passing, then the science requirement is not satisfied." It's still a mouthful, but a slightly more approachable mouthful.
✏️ The program below uses compound Booleans to plan activities for certain days and times of day. Try to change the conditionals so that it shows your own timed activities instead.
📝 See similar code in: App Lab | Snap | Python

## Logical operators ↔ logical gates

At the hardware level, computers implement logical operators using logic gates. A logic gate is a physical piece of hardware that performs an AND, OR, or NOT operation, as well as other Boolean operations.
Logic is a fundamental part of both computer hardware and computer software, so it's great that you're learning it now!

## Logical operators in pseudocode

The logical operators in pseudocode are very straightforward - they are written as `AND`, `OR`, and `NOT`:
ExpressionMeaning
`condition1 AND condition2`Evaluates to true if both `condition1` and `condition2` are true; otherwise evaluates to false.
`condition1 OR condition2`Evaluates to true if either `condition1` or `condition2` are true; evaluates to false only if both are false.
`NOT condition`Evaluates to true if `condition` is false; evaluates to false if `condition` is true.
Here are a few of the code snippets from above written in pseudocode:
``````IF (cspGrade ≥ 75 OR progGrade ≥ 75)
{
DISPLAY("You're eligible for AP CS A!")
}``````
``````IF (cumulativeGPA > 2.0 AND totalUnits ≥ 120)
{
}``````
``````IF (NOT(cumulativeGPA > 2.0 AND totalUnits ≥ 120))
{
sendEmail();
} ``````

## Want to join the conversation?

• I think my keyboard doesn't have the key for pipeline symbol to write the OR expression. Can someone show me how?
• It should be located above the Enter or Return key that you use to space down when typing a paragraph of text.

Traditionally, the key will type the character '\', or a backslash. However, if you hold down the Shift key and press the same key as before (the key that typed '\'), you should get the '|' character.
• Doens't the "OR" operator mean that only one expression has to be true?
• Yes, you're correct. The definition provided here is more precise.
• Why do we add ampersands? what exactly do they mean when it's added into the code? Also, are there times you'll need to add more or less than two ampersands for codes?
(1 vote)
• In Javascript, && compares two logical expressions and returns true only when both expressions evaluate to true (i.e. it returns false if either expression is false). This is often added into an if-statement to ensure that certain conditions are satisfied before running a block of code.

Javascript also contains the & operator which performs the bitwise AND operation on its inputs. Generally, you won't need to use any of the bitwise operators though.

Keep in mind that different languages have different syntaxes and this will not apply to every language.
• Program determines student pricing. The pricing will trigger price of 65.00 when a student has 4 full time months in a course . The student is not require to have net income or credits on a T1 Return to qualify for student price.

Would I write this code condition as follows.
if {{T1TuitionSlilps.Tuition[0].T2202Session[0].Fulltime}} > 4 && {{T1.NetIncopme.NetIncome}} > = 0 &&{{T1.TotalCredits..M[0]}} > = 0 (generate Student Price 65.00)

Have I used the && correctly?
(1 vote)
• Why is it "===" instead of "==" ?
(1 vote)
• "===" changes both variables into into the same variable type so it doesn't output an error.
for example
`1 == '1'`
outputs `false` but
`1 === '1'`
outputs `true`