9: Else, And, Or, Not

This lesson will allow you to do complex case-checking more elegantly, using two new parts of the Python language.

  • after an if «C» statement, an else statement executes only if C is false
  • you can combine boolean conditions using A and B, A or B, and not A

else

A common task in writing programs is that you want to test some condition, and take either one action or another action, depending on the condition is true or false. Earlier, an exercise asked you to do something if age was less than 0, and something else if age is not less than 0; the code was something like

if age >= 0:  
  print('You are not necessarily a time traveller')
if age < 0:
  print('You are a time traveller')
Now let's rewrite it to use else.

Example
 
You may enter input for the program in the box below.

More generally, you use else via the following pair of block statements:

if «test»:
   «true-body»        # an indented block
else:
   «false-body»       # another indented block
Python evaluates the test. If it is true the true-body is executed, and if it is false the false-body is executed.

The Philosophy of else

We don't get new powers from else, but it makes code much easier to read, debug, and maintain. Here are two code fragments that do the same thing:

Version A
if height < 256:
   print('Too short for this ride')
else:
   print('Welcome aboard!')
Version B
if height < 256:
   print('Too short for this ride')
if height >= 256:
   print('Welcome aboard!')

Both do the same thing, and B doesn't even need else. However, most programmers would agree that A is better. For example, with A, changing the condition (e.g., using 128 instead of 256) requires only one change to the code instead of two. Also, A can be immediately understood by a human reader, while in B you need to check and think whether or not both, or neither conditions can be true.

Coding Exercise: Absolute Value
The absolute value of a number is defined as follows. For a number x that is positive or zero, the absolute value of x is x. Otherwise, when x is a negative number, the absolute value of x is -x, or in other words the same as x but without the minus sign. For example the absolute value of 5 is 5, and the absolute value of -10 is 10. Using if and else, write a program that reads an integer as input, and prints its absolute value.
You may enter input for the program in the box below.

Python has a built-in function abs(x) to compute the absolute value of x. The grader above prevents you from using it, but you can use it later.

elif

Python introduces one other keyword, elif, to make it easier to check several conditions in a row. The most basic form of elif is the following:

if «test1»:
   «body1»        # runs if test1 is true
elif «test2»:
   «body2»        # runs if test1 is false and test2 is true
As you may have guessed, elif is short for "else if", since it is the same as putting an if statement inside an else block. But, it leads to shorter code and less indentation, which makes your program easier to read, debug, and edit. What's more, you can combine any number of elif statements in a row and even add an optional else statement to the end:

if «test1»:
   «body1»      # runs if test1 is true
elif «test2»:
   «body2»      # runs if test1 is false and test2 is true
elif «test3»:
   «body3»      # runs if test1 & test2 both false and test3 is true
else:           # these last two lines are optional
   «else-body»  # runs if ALL the tests are false
 

Here is an example of elif used inside of a loop. Can you predict the output before it runs?

Coding Exercise: First, Second, Third
The words 1st, 2nd, 3rd, 4th, 5th, 6th, 7th, 8th, 9th are called ordinal adjectives. Write a program which reads an integer x between 1 and 9 from input. The program should output the ordinal adjective corresponding to x.
Hint: you don't need to have 9 separate cases; 4 is enough.
You may enter input for the program in the box below.

Boolean Operators: and, or, not

You can combine boolean expressions using "and", "or", and "not", which are the same as in the English language.

  • The expression A and B is true if both A is true and B is true, and false if either is false. (For example, you get wet if it rains and you forgot your umbrella.)
  • The expression A or B is true if either A is true or B is true, and false if both are false. (For example, school is closed if it is a holiday or it is a weekend.)
  • The expression not A is true if A is false, and false if A is true. (For example, you are hungry if you have not eaten lunch.)

Here is a program which automatically displays all of the possibilities. Just like the 'multiplication tables' you remember from grade school, this is called a truth table.

Example
Truth tables

As an example of using and, here is a program which converts numbers to letters, with some error-checking.

Example
An example of and: Converting numbers to letters, with 1=A, 2=B, etc.
You may enter input for the program in the box below.

Coding Exercise: 26 Letters
Write a program which does the reverse of the example above: it should take a character as input and output the corresponding number (between 1 and 26). Your program should only accept capital letters. As error-checking, print invalid if the input is not a capital letter. HintAlternate string comparison method
You may enter input for the program in the box below.

Multiple Choice Exercise: De Morgan's Law
Which of the following expressions is equivalent to A or B?
Correct! Here is one way to arrive at this answer. First, not (A or B) is only true when both A and B are false. Also, note that (not A) and (not B) is only true if both not A and not B are true, i.e. if both A and B are false. So we have the following equality:
(not A) and (not B) = not (A or B)
Put a not around both sides, so we deduce
not ((not A) and (not B)) = not (not (A or B))
and observe that not(not X)) always equals X, so
not ((not A) and (not B)) = not (not (A or B)) = A or B
This way of rewriting a boolean expression is one of De Morgan's laws.

Order of Operations

Boolean operators have an "order of operations" just like mathematical operators. The order is

NAO: not (highest precedence), and, or (lowest precedence)

so for example,

not x or y and z means (not x) or (y and z)

We conclude the lesson with a short question using these facts.

Multiple Choice Exercise: Order of Operations
What is the value of

A or not B and C
if (A, B, C) = (False, True, True)? Hint
Correct! The order of operations makes this equivalent to
A or ((not B) and C)
substituting the values, we have
False or ((not True) and True)
and now simplifying one step at a time gives
False or ((not True) and True)
= False or (False and True)
= False or False
= False
Once you complete this, you are ready for the next lesson.