Python 4c - Logical Operators

AND Operator

We use the AND operator to execute certain code if more than one thing is true.

 

AND is commonly used with account logins - the username AND the password must be correct.

 

The example below requires a correct password and correct number:

If  neither or only one of these statements is true then the indented line will not be run:

If both statements are true then the indented line can be executed:

OR Operator

We use the OR operator to execute certain code if one of several statements is true. For example:

It is important that you re-write the variable each time you use the or operator.

 

It will not work if you just write: if vowel == “a” or “e” or “i” or “o” or “u”

 

Below is the program with two possible outputs:

Practice Task

1. Ask the user to enter their favourite colour and then ask them their age.

2. If their favourite colour is the same as yours AND their age is the same as yours then print “Snap! Are you my twin?”.

3. If only one of the statements is true (OR) then print “Spooky! You’re a bit like me.”

4. Add an else statement to print “We’re not so similar you and I”.

Example solution:

© CSNewbs 2019