Logical Operators

Logical operators are used to further enhance your conditional statements.

There are three conditional statements that you need to be able to use and identify within code.

And operators check multiple conditions and all of them must be true.

OR operators check multiple conditions and at least one must be true.

NOT operators reverse the logic of a condition.

Key Points

Logical Operators are applied to conditions.

AND checks for multiple conditions being true.

OR checks for at least one condition being true.

NOT reverses the condition.

How to use the AND operator

The AND operator allows code to check multiple conditions at once. All conditions must be true for the whole condition to be true.

In Python, this is done by adding the word ‘and’ between all conditions.

In the below example, the code checks to see if the age is greater than or equal to 18 AND if the user’s name is “John”.

if age >= 18 and name == "John":
    print("Access Granted!")

How to use the OR operator

The OR operator allows code to check multiple conditions at once, but at least one of those conditions must be true.

In Python, this is done by adding the word ‘or’ between all conditions.

In the below example, the code checks to see if the user’s favourite colour is either “Red” or “Blue”,

If the colour is “Red” the output is “That’s a great colour!”.

If the colour is “Blue” the output is also “That’s a great colour!”.

If the colour is anything else, there is no output.

if colour == "Blue" or colour == "Red":
    print("That's a great colour!")

How to use the NOT operator

The NOT operator reverses the condition. This is an alternative to using the != operator which has the same results.

Unlike AND and OR, in Python, the NOT operator is used writing the word not before a condition and wrapping the condition in brackets.

In the below example, the code checks to see if the user’s age is NOT equal to 18.

If the person is not equal to 18 the output is “You are not 18”.

if not(age == 18):
    print("You are not 18")

National 5 Requirements

You should be able to identify AND, OR and NOT operators within code.

You should be able to use AND, OR and NOT operators within your own code.