Lecture 4

Knowledge Check

What are the problems in the following program?

num = input("What is your favorite number? ")
print("The first three multiples of num are: ")
print("\tnum*1")
print("\tnum*2")
print("\tnum*3")

The sys module provides a very useful method called exit. It can be used to stop a program. How would you get access to the exit method in your program?

What is the result of the following Boolean expressions?

  1. 1000 >= 90
  2. -38.5 >= -13
  3. 5.4/4.5 == (5*5.4) / (5*4.5)
  4. '1000' >= '90'
  5. 'cat' > 'cats'
  6. 'cat' = 'Cat'
  7. 45 =< 1000

Boolean Expressions

Boolean expressions are expressions that evaluate to either True or False values. These are very useful for if statements, while loops, and other common tasks. Before we get to these though, we first need to discuss Boolean expressions. Boolean expressions can be:

Last time, we saw the first three kinds. Today, we will see the fourth kind of boolean expression.

Result of Logical Operator

Logical operators manipulate the result of boolean expressions. Python provides the standard three operators:

Operator Effect Example
and Connects two (or more) boolean expressions. Both expressions must be true for result to be true >>> a = 'It is raining cats and dogs.'
>>> 'cat' in a and a[0].isupper() and a.endswith('.')
True
>>> #this looks like a sentence about a cat
or Connects two (or more) boolean expressions. At least one expression must be true for result to be true >>> option = 5
>>> option == 3 or option == 5 or option == 7
True
>>> #option is one of the prime numbers less than 10
not Reverses the truth of a boolean expression >>> a = 'Here are a list of options:'
>>> not a.endswith('.')
True
>>> #a does not end with a period

Order of Operations Revisited

Now that we have seen many other operations, let's revisit the order of operations.

Order Operator(s) Description Category
1 () Parentheses General
2 variable.method(...), variable.attribute Accessing method and attributes/variables from a variable Python Classes
3 func(...) Calling a function Functions
4 () Parentheses General
5 - Unary negation (e.g. -x) Math Operators
6 ** Exponentiation
7 *, /, //, % Multiplication and the Divisions
8 +, - Addition and Subtraction
9 <, <=, >, >= Less than, Less than or equal to, Greater than, Greater than or equal to Relational Operators
10 ==, != Equal to, Not equal to
11 not Not operator Logical Operators
12 and And operator
13 or Or operator
14 =, **=, *=, /=, //=, %=, +=, -= Assignment operators Assignment Operators

What does the following evaluate to?

>>> total = 1500
>>> stock = 10
>>> warehouse = 1055
>>> found = False
>>> total != stock + warehouse or not found

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'
<< Previous Notes Daily Schedule Next Notes >>