Lecture 5

if Statements

Boolean expressions by themselves are not very useful. Their usefulness most often shows up in if statements and while loops. For now, we will talk about if statements.

if statements allow us to ask questions in Python and perform certain actions based on the result of the question. The "questions" we ask are in the form of Boolean expressions. The "actions performed" are Python statements that are executed based on whether the Boolean expression is True or False.

The simplest form of the if statement is:

if condition:
    #statements to execute if condition is True

The if statement starts with the Python keyword "if". What follows is the "condition" (a Boolean expression), then a colon. This can be called the if statement header. On the next line, you begin the body of the if statement. Each line of the body must be indented (a tab or four spaces is standard). The body consists of statements to execute if the condition is True. The first non-indented line ends the body. Here is an example:

num_sentences = 0
sentence = input("Please enter text: ")
if sentence[0].isupper() and sentence.endswith('.'):
    print("You entered a sentence.")
    num_sentences += 1
print("This line will always execute.")

Often, you will want to execute one block of code if the condition is True and another if it is False. This is possible with the if-else statement. It begins the same way as the if statement, but after the body of the if statement, you use the else keyword, followed by a colon. On the next line, the body of the else clause begins. Each line of the else clause must be indented; these lines will only execute if the condition is False.

num_sentences = 0
sentence = input("Please enter text: ")
if sentence[0].isupper() and sentence.endswith('.'):
    #this block is only executed if the clause is True
    print("You entered a sentence.")
    num_sentences += 1
else:
    #this block is only executed if the clause is False
    print("You did not enter a sentence.")

It is possible to nest if statements inside of other if statements (or else clauses):

total = 1.5
response = input("Do you want fries with your order? ")
if response.lower().startswith('y'):
    #they want fries, what what size?
    response = input("What size? (small, medium, or large) ")
    if response.lower() == 'small':
        total += 0.5
    if response.lower() == 'medium':
        total += 0.75
    if response.lower() == 'large':
        total += 1
else:
    #they don't want fries, but are they sure?
    response = input("Are you sure? ")
    if response.lower().startswith('n'):
        #This is just copied from above...it would be nice if we didn't have to duplicate code...how to avoid that coming soon
        response = input("What size? (small, medium, or large) ")
        if response.lower() == 'small':
            total += 0.5
        if response.lower() == 'medium':
            total += 0.75
        if response.lower() == 'large':
            total += 1

Sometimes, you're interested in more than just two possibilities. In the previous example, we were interested in three possibilities for the size of fries. There is a better option than three if statements: the if-elif-else statement.

#...
response = input("What size? (small, medium, or large) ")
if response.lower() == 'small':
    total += 0.5
elif response.lower() == 'medium':
    total += 0.75
else:
    total += 1

This is really helpful for mutually-exclusive options:

Just if-statements if-else statements if-elif-else statements
if grade > 100:
    letter_grade = 'A+'
if 93 <= grade and grade < 100:
    letter_grade = 'A'
if 90 <= grade and grade < 93:
    letter_grade = 'A-'
if 87 <= grade and grade < 90:
    letter_grade = 'B+'
if 83 <= grade and grade < 87:
    letter_grade = 'B'
if 80 <= grade and grade < 83:
    letter_grade = 'B-'
if 77 <= grade and grade < 80:
    letter_grade = 'C+'
if 73 <= grade and grade < 77:
    letter_grade = 'C
if 70 <= grade and grade < 73:
    letter_grade = 'C-'
if 67 <= grade and grade < 70:
    letter_grade = 'D+'
if 63 <= grade and grade < 67:
    letter_grade = 'D'
if 60 <= grade and grade < 63:
    letter_grade = 'D-'
if grade < 60:
    letter_grade = 'F'
if grade > 100:
  letter_grade = 'A+'
else:
  if 93 <= grade:
    letter_grade = 'A'
  else:
    if 90 <= grade:
      letter_grade = 'A-'
    else:
      if 87 <= grade:
        letter_grade = 'B+'
      else:
        if 83 <= grade:
          letter_grade = 'B'
        else:
          if 80 <= grade:
            letter_grade = 'B-'
          else:
            if 77 <= grade:
              letter_grade = 'C+'
            else:
              if 73 <= grade:
                letter_grade = 'C
              else:
                if 70 <= grade:
                  letter_grade = 'C-'
                else:
                  if 67 <= grade:
                    letter_grade = 'D+'
                  else:
                    if 63 <= grade:
                      letter_grade = 'D'
                    else:
                      if 60 <= grade:
                        letter_grade = 'D-'
                      else:
                        letter_grade = 'F'
if grade > 100:
    letter_grade = 'A+'
elif 93 <= grade:
    letter_grade = 'A'
elif 90 <= grade:
    letter_grade = 'A-'
elif 87 <= grade:
    letter_grade = 'B+'
elif 83 <= grade:
    letter_grade = 'B'
elif 80 <= grade:
    letter_grade = 'B-'
elif 77 <= grade:
    letter_grade = 'C+'
elif 73 <= grade:
    letter_grade = 'C
elif 70 <= grade:
    letter_grade = 'C-'
elif 67 <= grade:
    letter_grade = 'D+'
elif 63 <= grade:
    letter_grade = 'D'
elif 60 <= grade:
    letter_grade = 'D-'
else:
    letter_grade = 'F'

isinstance Function

At times, it is useful to ask what kind of data you're working with. Are you dealing with a number or with a string? The isinstance function may seem like the tool to use, but it isn't. The isinstance function takes two arguments: a variable and a datatype. It returns True if the variable is an instance of the datatype.

>>> a = 'asdf'
>>> isinstance(a, str)
True
>>> isinstance(a, int)
False
>>> isinstance(35, int)
True

The isinstance function does not tell you whether data of one type can look like data of another type.

>>> isinstance('1234', int)
False
>>> isinstance(35, float)
False

Basically, the isinstance function gives the same result as:

>>> a = 'asdf'
>>> type(a) == str #same as isinstance(a, str)
True
>>> type(a) == int #isinstance(a, int)
False

However, the isinstance function is faster than using the type function and equality operator.

The point of bringing this up is that programmers often want to know whether the user entered a number or text. You cannot use isinstance to determine that. input always returns a string. When we get to exception handling, we will see how to determine whether the user entered a number or just text.

Practice

The following programs are to practice writing if statements.

ISP Calculator

An internet service provider has three subscription packages for customers to choose from:

  1. Package A: For $9.95 per month, 10 hours of access are provided. Additional hours are $2.00 per hour.
  2. Package B: For $13.95 per month, 20 hours of access are provided. Additional hours are $1.00 per hour.
  3. Package C: For $19.95 per month, access is unlimited.

Write a program that calculates a customer's monthly bill. It must ask the user to enter the letter of the package they purchased (A, B, C) and the number of hours they used (the user does not have to enter a whole number). It should then display the total charges (formatted to look like a dollar amount).

If the user does not give you a valid subscription package (capitalization does not matter), tell them. If the number of hours they used is not positive, tell them.

Here is an example of what your program should look like when it runs (what the user types is in bold italics):

What package have you subscribed to? a
How many hours did you use? 13
Your total charge is $15.95.

Roman Numerals

Write a program that prompts the user to enter a number within the range of 1 through 10. The program should display the Roman numeral version of that number. If the number is outside the range of 1 through 10, the program should display an error message. The following table shows the Roman numerals for the numbers 1 through 10:

Number Roman Numeral
1 I
2 II
3 III
4 IV
5 V
6 VI
7 VII
8 VIII
9 IX
10 X

There are some more elegant ways to implement this, such as using dicts, but for now use if statements.

Roulette Wheel Colors

On a roulette wheel, the pockets are numbered from 0 to 36. The colors of the pockets are as follows:

Write a program that asks the user to enter a pocket number. Display whether the pocket is green, red, or black. Display an error message if the user enters a number that is outside of the range 0 through 36.

Body Mass Index

Write a program that calculates and displays a person's body mass index (BMI). The BMI can be used to determine whether someone is overweight or underweight for their height. A person's BMI is calculated with the formula:

BMI = weight * 703 / height2

where weight is measured in pounds and height is measured in inches.

The program should ask the user to enter their weight and height, then display the user's BMI. The program should also display a message indicating whether the person has optimal weight, is underweight, or overweight. Use the following guidelines:

<< Previous Notes Daily Schedule Next Notes >>