Metadata
Title
9: Else, And, Or, Not
Category
general
UUID
556494c042244a239801059fd75e8703
Source URL
https://cscircles.cemc.uwaterloo.ca/9-else-and-or-not/
Parent URL
https://cscircles.cemc.uwaterloo.ca/
Crawl Time
2026-03-18T05:13:46+00:00
Rendered Raw Markdown

9: Else, And, Or, Not

Source: https://cscircles.cemc.uwaterloo.ca/9-else-and-or-not/ Parent: https://cscircles.cemc.uwaterloo.ca/

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

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

age = int(input()) if age >= 0: print('You are not necessarily a time traveller') else: # instead of a second 'if'! print('You are a time traveller')

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 need to create an account and log in to ask a question.

x=int(input())

delete this comment and enter your code here

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

More actions... History Reset code to default Help

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 need to create an account and log in to ask a question.

delete this comment and enter your code here

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

More actions... History Help

Boolean Operators: and, or, not

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

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

print(" A B not A not B A and B A or B") print("----------------------------------------------") for A in [False, True]: # "for" loop with list for B in [False, True]: # will be taught in lesson 13 print(A, " ", B, " ", not A, " ", not B, " ", A and B, " ", A or B)

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.

x = int(input()) if x>=1 and x<=26: print('letter', x, 'in the alphabet:', chr(ord('A')+(x-1))) else: print('invalid input:', x)

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 need to create an account and log in to ask a question.

letter = input()

delete this comment and enter your code here

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

More actions... History Reset code to default Help

Multiple Choice Exercise: De Morgan's Law

Which of the following expressions is equivalent to A or B?

Your choice: Select one(not A) and (not B)not ((not A) and (not B))not (A and 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

Your choice: Select oneTrueFalse

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