7. Selection

Boolean Values and Boolean Expressions

The Python type for storing true and false values is called bool

  • Only two values: True and False.
In [1]:
print(True)
print(type(True))
print(type(False))
print("True")
print(type("True"))
True
<class 'bool'>
<class 'bool'>
True
<class 'str'>

boolean expression

A boolean expression is an expression that evaluates to a boolean value.

In [2]:
print(5 == 5)
print(5 == 6)
True
False

six common comparison operators

x == y      # x is equal to y
x != y      # x is not equal to y
x > y       # x is greater than y
x < y       # x is less than y
x >= y      # x is greater than or equal to y
x <= y      # x is less than or equal to y

Exercise

Which of the following is a Boolean expression? Select all that apply.
(A) True
(B) 3 == 4
(C) 3 + 4
(D) 3 + 4 == 7
(E) "False"

Logical operators

  • and
  • or
  • not
In [3]:
x = 5
print(x > 0 and x < 10)

n = 25
print(n % 2 == 0 or n % 3 == 0)
True
False
In [7]:
x, y, z = 1, 2, 3

print(x < y < z)

print(x == y == z)

print(x != y != z)
True
False
True

Exercise

1. Check if the value of num is 5,6, or 7, which is correct?
num == 5 or 6 or 7

num = 5 or num = 6 or num = 7

num == 5 or num == 6 or num == 7

num > 4 and num < 8
2. What is the correct Python expression for checking to see if a number stored in a variable x is between 0 and 5.
(A) x > 0 and < 5
(B) 0 < x < 5
(C) x > 0 or x < 5
(D) x > 0 and x < 5

Precedence of Operators

Level Category Operators
7(high) exponent **
6 multiplication *,/,//,%
5 addition +,-
4 relational ==,!=,<=,>=,>,<
3 logical not
2 logical and
1(low) logical or

Exercise

Which of the following properly expresses the precedence of operators (using parentheses) in the following expression: 5*3 > 10 and 4+6==11
(A) ((5*3) > 10) and ((4+6) == 11)
(B) (5*(3 > 10)) and (4 + (6 == 11))
(C) ((((5*3) > 10) and 4)+6) == 11
(D) ((5*3) > (10 and (4+6))) == 11

Conditional Execution: Binary Selection

In order to write useful programs, we almost always need the ability to check conditions and change the behavior of the program accordingly.

Selection statements, also referred to as conditional statements give us this ability.

The simplest form of selection is the if statement. This is sometimes referred to as binary selection since there are two possible paths of execution.

In [ ]:
x = 15

if x % 2 == 0:
    print(x, "is even")
else:
    print(x, "is odd")

The syntax for an if statement

if BOOLEAN EXPRESSION:
    STATEMENTS_1        # executed if condition evaluates to True
else:
    STATEMENTS_2        # executed if condition evaluates to False

Flowchart of a if statement with an else

Exercise

1. How many statements can appear in each block (the if and the else) in a conditional statement?
(A) Just one.
(B) Zero or more.
(C) One or more.
(D) One or more, and each must contain the same number.
2. What does the following code print (choose from output a, b, c or nothing).
if 4 + 5 == 10:
    print("TRUE")
else:
    print("FALSE")
(A) TRUE
(B) FALSE
(C) TRUE on one line and FALSE on the next
(D) Nothing will be printed
3. What does the following code print?
if 4 + 5 == 10:
    print("TRUE")
else:
    print("FALSE")
print("TRUE")

Omitting the else Clause: Unary Selection

In [ ]:
x = 10
if x < 0:
    print("The negative number ",  x, " is not valid here.")
print("This is always printed")
In [ ]:
x = -10
if x < 0:
    print("The negative number ",  x, " is not valid here.")
print("This is always printed")

Exercise: Will the following code cause an error?

x = -10
if x < 0:
    print("The negative number ",  x, " is not valid here.")
else:
    print(x, " is a positive number")
else:
    print("This is always printed")

Nested conditionals

In [ ]:
x, y = 1, 10
if x < y:
    print("x is less than y")
else:
    if x > y:
        print("x is greater than y")
    else:
        print("x and y must be equal")
In [1]:
from IPython.display import IFrame
IFrame('http://pythontutor.com/iframe-embed.html#code=x%20%3D%201%0Ay%20%3D%2010%0A%0Aif%20x%20%3C%20y%3A%0A%20%20%20%20print(%22x%20is%20less%20than%20y%22%29%0Aelse%3A%0A%20%20%20%20if%20x%20%3E%20y%3A%0A%20%20%20%20%20%20%20%20print(%22x%20is%20greater%20than%20y%22%29%0A%20%20%20%20else%3A%0A%20%20%20%20%20%20%20%20print(%22x%20and%20y%20must%20be%20equal%22%29&codeDivHeight=400&codeDivWidth=350&cumulative=false&curInstr=0&heapPrimitives=false&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false', width='100%', height=450)
Out[1]:

Exercise: Will the following code cause an error?

x = -10
if x < 0:
    print("The negative number ",  x, " is not valid here.")
else:
    if x > 0:
        print(x, " is a positive number")
    else:
        print(x," is 0")

Chained conditionals

an alternative way to write nested selection: elif

if x < y:
    print("x is less than y")
elif x > y:
    print("x is greater than y")
else:
    print("x and y must be equal")
In [ ]:
x = 1
y = 10

if x < y:
    print("x is less than y")
elif x > y:
    print("x is greater than y")
else:
    print("x and y must be equal")

Exercise

What is the result of following code?

In [ ]:
# code 1
x = -10
if x < 0:
    print("The negative number ",  x, " is not valid here.")
else:
    if x > 0:
        print(x, " is a positive number")
    else:
        print(x, " is 0")
In [ ]:
# code 2

if x < 0:
    print("The negative number ",  x, " is not valid here.")
else x > 0:
    print(x, " is a positive number")
else:
    print(x, " is 0")
In [ ]:
# code 3

if x < 0:
    print("The negative number ",  x, " is not valid here.")
elif x > 0:
    print(x, " is a positive number")
else:
    print(x, " is 0")
In [ ]:
# code 4

if x < 0:
    print("The negative number ",  x, " is not valid here.")
if x > 0:
    print(x, " is a positive number")
else:
    print(x, " is 0")

Exercise

What will the following code print if x = 3, y = 5, and z = 2?
if x < y and x < z:
    print("a")
elif y < x and y < z:
    print("b")
else:
    print("c")

Boolean Functions

In [ ]:
def isDivisible(x, y):
    if x % y == 0:
        result = True
    else:
        result = False

    return result

print(isDivisible(10, 5))
In [ ]:
def isDivisible(x, y):
    return x % y == 0

Boolean functions are often used in conditional statements:

if isDivisible(x, y):
    ... # do something ...
else:
    ... # do something else ...
In [ ]:
def isDivisible(x, y):
    if x % y == 0:
        result = True
    else:
        result = False

    return result

if isDivisible(10, 5):
    print("That works")
else:
    print("Those values are no good")
In [2]:
from IPython.display import IFrame
IFrame('http://pythontutor.com/iframe-embed.html#code=def%20isDivisible(x,%20y%29%3A%0A%20%20%20%20if%20x%20%25%20y%20%3D%3D%200%3A%0A%20%20%20%20%20%20%20%20result%20%3D%20True%0A%20%20%20%20else%3A%0A%20%20%20%20%20%20%20%20result%20%3D%20False%0A%0A%20%20%20%20return%20result%0A%0Aif%20isDivisible(10,%205%29%3A%0A%20%20%20%20print(%22That%20works%22%29%0Aelse%3A%0A%20%20%20%20print(%22Those%20values%20are%20no%20good%22%29&codeDivHeight=400&codeDivWidth=350&cumulative=false&curInstr=0&heapPrimitives=false&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false', width='100%', height=450)
Out[2]:

Exercise

1. What is a Boolean function?
(A) A function that returns True or False
(B) A function that takes True or False as an argument
(C) The same as a Boolean expression
2. Is the following statement legal in Python (assuming x, y and z are defined to be numbers)?
return x + y < z
(A) Yes
(B) No
4. Give the logical opposites of these conditions. You are not allowed to use the not operator.
a > b
a >= b
a >= 18  and  day == 3
a >= 18  or  day != 3
5. Approximate the value of pi using Monte Carlo Simulation.

5. Write a function which is given an exam mark, and it returns a string — the grade for that mark — according to this scheme:
Mark Grade
>= 90 A
[80-90) B
[70-80) C
[60-70) D
< 60 F
6. Write a function is_rightangled which, given the length of three sides of a triangle, will determine whether the triangle is right-angled.

Glossary

block

A group of consecutive statements with the same indentation.

body

The block of statements in a compound statement that follows the header.

boolean expression

An expression that is either true or false.

boolean function

A function that returns a boolean value. The only possible values of the bool type are False and True.

boolean value

There are exactly two boolean values: True and False. Boolean values result when a boolean expression is evaluated by the Python interepreter. They have type bool.

branch

One of the possible paths of the flow of execution determined by conditional execution.

chained conditional

A conditional branch with more than two possible flows of execution. In Python chained conditionals are written with if ... elif ... else statements.

comparison operator

One of the operators that compares two values: ==, !=, >, <, >=, and <=.

condition

The boolean expression in a conditional statement that determines which branch is executed.

conditional statement

A statement that controls the flow of execution depending on some condition. In Python the keywords if, elif, and else are used for conditional statements.

logical operator

One of the operators that combines boolean expressions: and, or, and not.

modulus operator

An operator, denoted with a percent sign ( %), that works on integers and yields the remainder when one number is divided by another.

nesting

One program structure within another, such as a conditional statement inside a branch of another conditional statement.

In [ ]: