Week 4: Conditionals

Reading: Think Python Chapter 5

Notes

Comparison Expressions

Is 6 greater than 5? Obviously yes.

In Python, comparisons between values are accomplished with expressions using comparison operators.

6 > 5
True

These expressions return special values True and False. Be careful: these are not the same as strings "True" and "False". You can access them directly by typing True or False without any quotation marks.

True and False are Boolean variables, or “Bools” for short. There are only two Bools: True and False. Ambiguity can exist in society and philosophy, but it is not permitted in Python.

There are six comparison operators:

  • > (greater than)
  • >= (greater than or equal to)
  • < (less than)
  • <= (less than or equal to)
  • == (equal to)
  • != (not equal to)
Equality and Assignment

Take care with the difference between = and ==.

  • = (single equals) is assignment:
    • The expression on the right of the = is evaluated
    • The result is assigned to the variable on the left
  • == (double equals) is equality comparison:
    • Expressions on the left and right of == are compared
    • If they are equal, the comparison returns True
    • Otherwise, the comparison returns False

Comparison between numbers is straightforward:

7 < 7
False
7 <= 6 + 1
True
x = 3 + 1
x == 4.0
True

Floats are equal to ints when they are numerically exactly equal.

x == 4.000001
False
x = 5 + 2
x != 7
False

Equality can be used between almost any two values:

3 == "3"
False

The above expression is False because the string "3" is not numerically equal to the integer 3!

a = "finesse"
a == "finesse"
True

Strings are equal when they are the same.

x = print("finesse")
finesse

String comparison checks for alphabetical order if all letters are lowercase or all letters are uppercase. c comes before e in the alphabet, so the position of c is “less than” the position of e.

s = 'espresso'
s > 'cappuccino'
True

Equality can be used to check if something is None.

x == None
True

Remember, True and False are not strings:

True == "True"
False

Some comparisons make no sense, such as between strings and numbers. If you try these, you’ll get an error.

Conditional Execution

Comparison expressions enable us to execute code only if certain conditions are met.

We use the keyword if, a colon, and an indented code block. Similar to function definition syntax, the if statement controls execution of the indented block.

After the keyword if is a conditional expression. If the expression evaluates to True, the controlled block runs:

if_true.py
if True:
    print("this is controlled by the if statement")

print("this is outside the if statement")
this is controlled by the if statement
this is outside the if statement

If the expression does not evaluate to True, the controlled block doesn’t run:

if_false.py
if False:
    print("this is controlled by the if statement")

print("this is outside the if statement")
this is outside the if statement

The simple True and False above are just to illustrate how if statements work. Any valid conditional expression can come after the if keyword:

if_statement.py
x = 3
if (x > 2 + 1):
    print("this is controlled by the if statement")

print("this is outside the if statement")
this is outside the if statement

The parentheses are optional, but they help organize the code. Another example:

two_ifs.py
x = 2
if (x > 3):
    print("x is greater than three")

if (x < 3):
    print("x is less than three")

Trace through the execution. With x = 2, line 3 will not run (because x > 3 is False), and line 6 does run (because x < 3 is True).

Try editing the code and changing the value of x. What happens with x set to 0. Why?

else and elif

The if keyword can be grouped with other keywords to executed code when the expression after the if is False:

if_else.py
x = 2
if (x > 3):
    print("x is greater than three")
else:
    print("x is three or less")

With an if-else group, the code controlled by the else executes if the conditional expression for the if statement is not True. Exactly one of the two will execute.

Trace through the execution:

It’s common to want to perform another conditional check after the first check. Conditionals can be nested in Python:

if_else.py
x = 2
if (x > 3):
    print("x is greater than three")
else:
    if (x >= 1):
        print("x is between one and three")
    else:
        print("x is less than one")

Instead of nesting, however, we can use the conditional keyword elif (“else if”):

if_else.py
x = 2
if (x > 3):
    print("x is greater than three")
elif (x > = 1)
    print("x is between one and three")
else:
    print("x is less than one")

Rules for if-elif-else statements:

  • The if statement must come first
    • if includes a conditional expression
    • The if will run if the expression is True
  • elif statements come next
    • elif statements are optional (you can have zero)
    • Each elif includes a conditional expression
    • Each elif will be checked if the statement before it was False
    • An elif runs if its expression is True
  • An else (optionally) is last
    • else does not have a conditional expression
    • If every statement before the else was False, the else runs

Each statement and expression is evaluated in order. As soon as one expression is True (or we the else is reached), the code block it controls will run, and the group of statements is exited.

Practice

Practice Problem 4.1

Practice Problem 4.1

Write a function two_four that takes one argument, a number, and prints whether or not the number is between 2 and 4 (inclusive of 2 and 4):

  • two_four(5) results in printed output “5 is not between 2 and 4”
  • two_four(3.1) results in printed output “3.1 is between 2 and 4”
practice1_4_1.py
def two_four(input_number):
    # check if the number is greater than 4
        # if so, print something
    # if not, check if it is greater than or equal to 2
        # if so, print something
    # otherwise:
    #    print something

Hint: The comments in the code above outline the form of code that implements the function.

Practice Problem 4.2

Practice Problem 4.2

Implement the function two_four with the exact same behavior, using a different set of conditional statements.

Practice Problem 4.3

Practice Problem 4.3

Write a function that takes an argument, which could be a number or a string.

  • If the argument is a string, print "It's a string."

  • If the argument is a number, check if the number is positive.

    • If the number is positive, print "It's a positive number."
    • If the number is negative, print "It's a negative number."
    • If the number is zero, print "It's zero."

You can use the type function to inspect the type of variables.

type(2.3)
float

The output can be used in a conditional expression:

type('this is a string') == str
True

Practice Problem 4.4

Practice Problem 4.4

Write a function that takes as argument a number and rounds that number to the closest int.

Do this without using Python’s built-in round function.

Homework

  • Homework problems should always be your individual work. Please review the collaboration policy and ask the course staff if you have questions.

  • Double check your file names and printed output. These need to be exact matches for you to get credit.

Homework Problem 4.1

Homework Problem 4.1 (20 pts)

Write a function smart_root that takes one argument, a number.

If the number is not negative, print the number’s square root, rounded down to the nearest int.

If the number is negative, print The number is negative

Examples:

  • smart_root(4) prints 2
  • smart_root(2) prints 1
  • smart_root(1) prints 1
  • smart_root(-1) prints The number is negative

Submit as smart_root.py.

Homework Problem 4.2

Homework Problem 4.2 (20 pts)

Write a function check_square that takes one argument, a positive integer:

  • If the integer is a perfect square, print Perfect square!

  • Otherwise, print Not a perfect square.

  • check_square(4) prints Perfect square!

  • check_square(9) prints Perfect square!

  • check_square(10) prints Not a perfect square.

(A perfect square is a number that is the product of an integer multiplied by itself.)

Submit as check_square.py

  1. math.sqrt always returns a float
  2. Calling the math.sqrt function on a perfect square will return a float that is equal to an integer
    • math.sqrt(9) returns 3.0
  3. Calling math.sqrt on a number that isn’t a perfect square returns a float not equal to an integer
    • math.sqrt(10) returns 3.1622776601683795

Homework Problem 4.3

Homework Problem 4.3 (20 pts)

The function polarity is intended to check if a number is positive, negative, or zero, and print the result in the following format:

  • polarity(4) prints Positive.
  • polarity(-2) prints Negative.
  • polarity(0) prints Zero.

Here is the draft function. It does not quite work. Fix it!

polarity.py
# initial comments here
def polarity(v):
    if v >= 0:
        print("Positive.")
    elif v < 0:
        print("Negative.")
    else:
        print(0)

Submit as polarity.py.

Homework Problem 4.4

Homework Problem 4.4 (20 pts)

Write a function positioner that takes as argument a number. Your function should compare this number to three other numbers: 2, 12, and 21, and print the result of the comparison as the numbers in order, separated by spaces. Here are examples of the format:

  • positioner(3) prints 2 3 12 21
  • positioner(1) prints 1 2 12 21
  • positioner(15) prints 2 12 15 21
  • positioner(200) prints 2 12 21 200
  • positioner(12) prints 2 12 12 21

The input argument is printed in numerical order along with 2, 12, and 21. There are spaces between each pair of numbers; there is no space at the end of the sequence.

Submit as positioner.py.

Homework Problem 4.5

Homework Problem 4.5 (20 pts)

Write a function closer_to_zero that takes as argument a number.

  • If the number is positive, subtract one from it.
  • If the number is negative, add one to it.
  • If the number is zero, leave it unchanged.
  • At the end, print the number.

Examples:

  • closer_to_zero(4) prints 3
  • closer_to_zero(-2) prints -1
  • closer_to_zero(0) prints 0

Submit as closer_to_zero.py.