2016 September 14,

CS 111: Conditionals

In this section, we start writing Python code that is able to alter its behavior based on the information at hand. This is a huge first step toward writing interesting programs!

For example, suppose that I want to compute the absolute value of a number. For a positive number (such as 3), the absolute value is the same as the number (3). For a negative number (such as -5.8), the absolute value is the negative of that number (--5.8 = 5.8). We can implement this idea in Python as follows.

number = -5.8
if number >= 0:
    absval = number
else:
    absval = -number
print(absval)

Execute that program. Then change -5.8 to other values — both positive and negative, both integers and floating-point numbers — to observe how the behavior of the program changes.

Here's new code for making a string lower-case. How does it work, and how is it better than our old code?

string = 'JDAVISTHEDOLPHINARRIVESATMIDNIGHTYOURFRIENDJBIEBER'
result = ''
for character in string:
    if (character < 'a'): 
        result = result + chr(ord(character) + 32)
    else:
        result = result + character
print(result)

Often, a program's logic is too complicated to capture with a single if statement. For example, suppose that an insurance company sets its auto insurance rates based on the driver's age. Drivers under 18 or over 90 are risky; drivers 18-25 are less risky; drivers 25-90 are the least risky of all. We can implement this idea by nesting if statements. Run the following code, trying various ages.

age = 31
if age < 18:
    rate = 450
else:
    if age > 90:
        rate = 500
    else:
        if age < 25:
            rate = 400
        else:
            rate = 300
print(rate)

Question 09A: Suppose that the program is run with age 17. Exactly which of the three if statements gets executed? What if the age is 19? What if it's 50? What if it's 150?

In fact, such nested combinations of else and if are so common, that there is a shortcut, elif, for dealing with them. The following code is equivalent, but a bit easier to type.

age = 31
if age < 18:
    rate = 450
elif age > 90:
    rate = 500
elif age < 25:
    rate = 400
else:
    rate = 300
print rate

Now that we are starting to write programs with a lot of indentations, you need to know something: Python is very sensitive to indentations. All of the code within a single indented block must be indented in exactly the same way. If not, then Python complains or (worse) your program does the wrong thing without any complaint.

Question 09B: What's wrong with the following code? How do you fix it?

age = 31
if age < 18:
    rate = 450
else:
    if age > 100:
        rate = 500
    else:
        if age < 25:
            rate = 400
         else:
            rate = 300
print(rate)