Learn

In this exercise, we will take a look at logical operators.

Logical operators allow us to combine multiple True/False expressions and statements into complex conditionals. Using the operators -and, -or, -xor, -not, !, we can test multiple conditions with the equality comparison operators we discussed in the previous exercise.

Truth Table

A simple way to show the output of logical operators is through a truth table.

x y x -and y x -or y x -xor y -not x
T T T T F F
T F F T T F
F T F T T T
F F F F F T

As shown in the first two columns, imagine x and y are variables that hold the boolean values. The rest of the columns show the output of the corresponding logical operator given the values for x and y for that row. Let’s explore a few PowerShell examples.

-and

The and logical operator is a binary operator that returns True if both statements are True.

PS > -5 -lt 7 -and "hello" -eq "hello" True PS > -5 -lt 7 -and "hello" -eq "world" False
-or

The binary or logical operator returns True if either statement returns True.

PS > 42 -le 13 -or 5 -ge 5 True PS > 42 -le 13 -or 5 -gt 5 False
-xor

This binary operator returns True when only ONE statement is True.

PS > 25 -gt 2 -xor "hello" -eq "world" True PS > 25 -gt 2 -xor "code" -eq "code" False
-not and !

Both the -not and ! operators negate the statement that follows. They are unary operators.

PS > -not (2 -gt 5) True PS > !(17 -le 99) False

Instructions

1.

In the logical_operators.ps1 script file, check if both variables $number_1 and $number_2 are less than 50. Assign the boolean result to a variable called $both_are_less_than_50.

When you’re done, click the Run button.

2.

Check whether the variable $number_1 OR $number_2 is greater than 100. Make the variable $one_is_higher_than_100 equal to its result.

When you’re done, click the Run button.

3.

Check whether ONLY one variable $number_1 or $number_2 is less than or equal to 10 and assign the result to a variable $only_one_is_less_than_10.

When you’re done, click the Run button.

4.

Using one of the two logical operators for negation, -not or !, verify that the variable $name is not equal to the string ‘codecademy’. Make the boolean variable $name_is_not_codecademy equal to its result.

When you’re done, click the Run button.

5.

Run the script from the terminal by typing ./logical_operators.ps1. To check your work, click the Run button.

When prompted, enter your name and any two integers. Press Enter to confirm.

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?