top of page
top

Python 4c - Logical Operators

AND Operator

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:

py9.png

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

py10.png

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

py11.png

OR Operator

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

py12.png

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 letter == “a” or “e” or “i” or “o” or “u”

 

Below is the program with two possible outputs:

py13.png
py14.png

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:

py22.PNG
bottom of page