Think Python for CS114

Chapter 8 Conditional execution

In order to write useful programs, we almost always need the ability to check conditions and change the behavior of the program accordingly. Conditional statements give us this ability. The simplest form is the if statement:

if x > 0:
    print('x is positive')

The boolean expression after if is called the condition. If it is true, the indented statement runs. If not, nothing happens.

if statements have the same structure as function definitions: a header followed by an indented body. Statements like this are called compound statements.

There is no limit on the number of statements that can appear in the body, but there has to be at least one. Occasionally, it is useful to have a body with no statements (usually as a place keeper for code you haven’t written yet). In that case, you can use the pass statement, which does nothing.

if x < 0:
    pass          # TODO: need to handle negative values!

8.1 Alternative execution

A second form of the if statement is “alternative execution”, in which there are two possibilities and the condition determines which one runs. The syntax looks like this:

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

If the remainder when x is divided by 2 is 0, then we know that x is even, and the program displays an appropriate message. If the condition is false, the second set of statements runs. Since the condition must be true or false, exactly one of the alternatives will run. The alternatives are called branches, because they are branches in the flow of execution.

8.2 Chained conditionals

Sometimes there are more than two possibilities and we need more than two branches. One way to express a computation like that is a chained conditional:

if x < y:
    print('x is less than y')
elif x > y:
    print('x is greater than y')
else:
    print('x and y are equal')

elif is an abbreviation of “else if”. Again, exactly one branch will run. There is no limit on the number of elif statements. If there is an else clause, it has to be at the end, but there doesn’t have to be one.

if choice == 'a':
    draw_a()
elif choice == 'b':
    draw_b()
elif choice == 'c':
    draw_c()

Each condition is checked in order. If the first is false, the next is checked, and so on. If one of them is true, the corresponding branch runs and the statement ends. Even if more than one condition is true, only the first true branch runs.

8.3 Nested conditionals

One conditional can also be nested within another. We could have written the example in the previous section like this:

if x == y:
    print('x and y are equal')
else:
    if x < y:
        print('x is less than y')
    else:
        print('x is greater than y')

The outer conditional contains two branches. The first branch contains a simple statement. The second branch contains another if statement, which has two branches of its own. Those two branches are both simple statements, although they could have been conditional statements as well.

Although the indentation of the statements makes the structure apparent, nested conditionals become difficult to read very quickly. It is a good idea to avoid them when you can.

Logical operators often provide a way to simplify nested conditional statements. For example, we can rewrite the following code using a single conditional:

if 0 < x:
    if x < 10:
        print('x is a positive single-digit number.')

The print statement runs only if we make it past both conditionals, so we can get the same effect with the and operator:

if 0 < x and x < 10:
    print('x is a positive single-digit number.')

For this kind of condition, Python provides a more concise option:

if 0 < x < 10:
    print('x is a positive single-digit number.')

8.4 Boolean functions (predicates)

Functions can return booleans, which is often convenient for hiding complicated tests inside functions.

This is so common that it is given a special name: a function that returns a boolean is often called a predicate, or a predicate function.

For example:

def is_divisible(x: int, y: int) -> bool:
    if x % y == 0:
        return True
    else:
        return False

It is common to give boolean functions names that sound like yes/no questions; is_divisible returns either True or False to indicate whether x is divisible by y.

Here is an example:

>>> is_divisible(6, 4)
False
>>> is_divisible(6, 3)
True

The result of the == operator is a boolean, so we can write the function more concisely by returning it directly:

def is_divisible(x: int, y: int) -> bool:
    return x % y == 0

Boolean functions are often used in conditional statements:

if is_divisible(x, y):
    print('x is divisible by y')

It might be tempting to write something like:

if is_divisible(x, y) == True:
    print('x is divisible by y')

But the extra comparison is unnecessary.

As an exercise, write a function is_between(x, y, z) that returns True if xyz or False otherwise.

There are many built-in predicates in Python. One interesting one is isinstance. We can use this to check the type of a value, and even to treat different types differently:

def describe_type(x):
    if isinstance(x, int):
        return "x is an integer"
    elif isinstance(x, float):
        return "x is a float"
    elif isinstance(x, str):
        return "x is a str"

We might be tempted to use the type function in a situation like this. But this is not a good idea. Python is an object oriented programming language, and supports inheritance; this means that for example something could be “a kind of int” instead of literally being an int. The type function ignores inheritance, while isinstance works with it in a sensible manner.

8.5 Debugging

When a syntax or runtime error occurs, the error message contains a lot of information, but it can be overwhelming. The most useful parts are usually:

  • What kind of error it was, and

  • Where it occurred.

Syntax errors are usually easy to find, but there are a few gotchas. Whitespace errors can be tricky because spaces and tabs are invisible and we are used to ignoring them.

>>> x = 5
>>>  y = 6
  File "<stdin>", line 1
    y = 6
    ^
IndentationError: unexpected indent

In this example, the problem is that the second line is indented by one space. But the error message points to y, which is misleading. In general, error messages indicate where the problem was discovered, but the actual error might be earlier in the code, sometimes on a previous line.

The same is true of runtime errors. Suppose you are trying to compute a signal-to-noise ratio in decibels. The formula is SNRdb=10log10(Psignal/Pnoise). In Python, you might write something like this:

import math
signal_power = 9
noise_power = 10
ratio = signal_power // noise_power
decibels = 10 * math.log10(ratio)
print(decibels)

When you run this program, you get an exception:

Traceback (most recent call last):
  File "snr.py", line 5, in ?
    decibels = 10 * math.log10(ratio)
ValueError: math domain error

The error message indicates line 5, but there is nothing wrong with that line. To find the real error, it might be useful to print the value of ratio, which turns out to be 0. The problem is in line 4, which uses floor division instead of floating-point division.

You should take the time to read error messages carefully, but don’t assume that everything they say is correct.

8.6 Glossary

boolean expression:

An expression whose value is either True or False.

relational operator:

One of the operators that compares its operands: ==, !=, >, <, >=, and <=.

logical operator:

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

conditional statement:

A statement that controls the flow of execution depending on some condition.

condition:

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

compound statement:

A statement that consists of a header and a body. The header ends with a colon (:). The body is indented relative to the header.

branch:

One of the alternative sequences of statements in a conditional statement.

chained conditional:

A conditional statement with a series of alternative branches.

nested conditional:

A conditional statement that appears in one of the branches of another conditional statement.

return statement:

A statement that causes a function to end immediately and return to the caller.

Exercise 8.1.

If you are given three sticks, you may or may not be able to arrange them in a triangle. For example, if one of the sticks is 12 inches long and the other two are one inch long, you will not be able to get the short sticks to meet in the middle. For any three lengths, there is a simple test to see if it is possible to form a triangle:

If any of the three lengths is greater than the sum of the other two, then you cannot form a triangle. Otherwise, you can. (If the sum of two lengths equals the third, they form what is called a “degenerate” triangle.)

  1. 1.

    Write a function named is_triangle that takes three integers as arguments, and that prints either “Yes” or “No”, depending on whether you can or cannot form a triangle from sticks with the given lengths.

  2. 2.

    Write a function that prompts the user to input three stick lengths, converts them to integers, and uses is_triangle to check whether sticks with the given lengths can form a triangle.