Python Beginners – And-Or-Not

Python Beginners – And-Or-Not; is the penultimate tutorial in this beginner’s series. First, it covers using the remaining logical operators (not, and, or). Secondly, it looks at how to combine multiple logic operators into a single statement. Then finally, it will look at some potential pitfalls when using logic. There is a video version of this post at the bottom of the blog or by clicking here.

Python supports three logic operators:

  • AND
  • OR
  • NOT

Logical operators are boolean logic. Meaning every result is either True or False. Logical operators are typically taught alongside logic gates. This tutorial will touch on logic gates but not dwell on them since there are more logic gates than logic operators in Python.

Previous Logic Recap

Previously we looked at the following operators

Operator Description
==Equivalent to
<Less than
>Greater than
<=Less than or equal to
>=Greater than or equal to
Table of basic logic operators

Using the logic above, we can write a statement like “five is less than 10” as “5 < 10”, then say that the statement is True or False. E.g.

isLessThan = bool (5<10)
print(isLessThan)

Will output

True

While the following

isLessThan = bool (10<10)
print(isLessThan)

Will output False.

If you need more direction with these operators, please go back to Python Beginners – Selection.

AND Logic Operator – Python Beginners – And-Or-Not

The AND operator takes in two boolean values (True or False) and outputs True only when both the inputs are True. Otherwise, it will output False. The image below shows the AND logic gate and the truth table with inputs and outputs.

In Python code, this is written similarly to other boolean logic. E.g.

a = True
b = False
aAndb = a and b
print(aAndb)

Outputs

False

Whereas

a = True
b = True
aAndb = a and b
print(aAndb)

Outputs

True

Finally, let us turn that into some functional code. The example below creates a boolean that checks the date and month to see if it is a leap year.

month = "February"
dayOfMonth = 29
leapYear = (dayOfMonth == 29) and (month == "February")
print(leapYear)

This logic has several flaws, which will be covered in the last topic at the end of this tutorial. For now, let’s extend this code a little.

month = "February"
dayOfMonth = 29
leapYear = (dayOfMonth == 29) and (month == "February")
print(leapYear)
if leapYear:
    print("Its a leap year")
else:
    print("Its not a leap year")

Hopefully, some of you have spotted the gaping hole in this logic. Essentially it says that if it is not the 29th and February, it is not a leap year. Every leap year has 365 other days other than the 29th of February. You can use all logic operators in an ‘if’ statement and a ‘while’ loop. These are typically included in the selection or loop criteria. E.g.

month = "February"
dayOfMonth = 29
if (dayOfMonth == 29) and (month == "February"):
    print("Its a leap year")
else:
    print("Its not a leap year")

Better Logic

Finally, let us look at an example with sound logic. In the UK, attending school between the ages of 5 and 16 is compulsory. So if we want to select school-age people from a list, we could write the following program. It says that if the age is greater than or equal to 5 and less than or equal to 16, then print “school age”; otherwise, print “not school age.”

ages = [2, 50, 80, 12, 9, 30, 6, 10]
for age in ages:
    if age >= 5 and age <= 16:
        print("School age")
    else:
        print("Not school age")

However, this code can be improved by adjusting the logic expression. The code below gives the same results but with less work. Differently, the logic states that 5 is less than or equal to age, and age is less than or equal to 16. However, you will notice that the ‘AND’ operator is not present.

ages = [2, 50, 80, 12, 9, 30, 6, 10]
for age in ages:
    if 5 <= age <= 16:
        print("School age")
    else:
        print("Not school age")

OR Logic Operator – Python Beginners – And-Or-Not

he OR operator takes in two boolean values (True or False) and outputs True only when either or both inputs are True. It only outputs False if both inputs are False.

The OR operator in Python is almost identical to the AND operator seen above. E.g.

a = True
b = False
aOrB = a or b
print(aOrB)

Outputs

True

Alternatively

a = False
b = False
aOrB = a or b
print(aOrB)

Outputs

False

Like the AND operator, it is typically written as part of an if statement. For example, we could write some logic that if it is raining or cold, then take a coat. E.g.

cold = True
rain = False
if rain or cold:
    print("Take a coat")
else:
    print("Don't take a coat")

Similarly to the first AND logic, this logic has issues. However, it shows how the OR operator can be used to make a decision. It wouldn’t work in many situations, such as someone staying inside.

By thinking differently, using the OR gate to solve the same school-age problem above is possible. This time the if statement will look for people that are either under 5 OR over 16

ages = [2, 50, 80, 12, 9, 30, 6, 10]
for age in ages:
    if age < 5 or age > 16:
        print("Not school age")
    else:
        print("School age")

NOT Operator – Python Beginners – And-Or-Not

The NOT logic operator has a single input and a single output. It inverts the input, meaning if the input is True, the output is False and vice versa.

The NOT operator in Python code works in basically the same way as the last two examples; however, there is only one input. E.g.

a = True
notA = not a
print(notA)

Outputs

False

The input started as True, so the output is false. Differently, the example below

a = False
notA = not a
print(notA)

Outputs

True

Like the previous logic operators, the NOT operator is usually written directly in a while loop or selection statement. Compare and experiment with the code below.

a = 10
b = 10
if a == b:
    print("A is equivalent to B")
else:
    print("A is not equivalent to B")

And

a = 10
b = 10
if not(a == b):
    print("A is equivalent to B")
else:
    print("A is not equivalent to B")

The not operator reverses the result of ‘a==b’, so the print statements must swap to keep the code working as expected. E.g.

a = 10
b = 10
if not(a == b):
    print("A is not equivalent to B")
else:
    print("A is equivalent to B")

Finally, here is a more everyday example of using a NOT operator. The logic here states that if it is raining AND cold, then take a coat. Else if it is raining but not cold, take an umbrella. Otherwise, forget about coats and umbrellas.

rain = True
cold = False
if rain and cold:
    print("take a coat")
elif rain and not cold:
    print("take an umbrella")
else:
    print("forget about a coat or umbrella")

Combining Multiple operators – Python Beginners – And-Or-Not

Logic becomes immensely powerful when logical operators are combined. However, it becomes much more complicated as well. Take a look at the example below. Try and work out what you think the result will be before you run it. Then experiment.

bankBalance = 1000000000
oldEnglishBillion = 1000000000000
americanBillion = 1000000000
nationality = "British"
traditionalist = False
british = bool(nationality == "British")
if ((bankBalance > oldEnglishBillion) and british and traditionalist) or (bankBalance >= americanBillion and (not (british and traditionalist))):
    print("Billionaire")
else:
    print("Not billionaire")

The output is:

Billionaire

Explanation

The logic above states the following. If the bank balance is greater than or equal to the old English Billion, AND they are British, AND they hold traditional values, they will consider themself a billionaire.

Alternatively, everyone else with a bank balance greater than or equal to the American billion will consider themself to be a billionaire unless they are British and have Traditional values.

Anyone not covered by the above statements will not consider themself to be a billionaire.

Video Version

Related Articles – Python Beginners – And-Or-Not

Related Post

9 thoughts on “Python Beginners – And-Or-Not

Leave a Reply

Your email address will not be published. Required fields are marked *