Module 0.4 - Conditionals

Objectives

By the end of this module you will be able to:

  • Mentally execute (trace) code with conditionals: if, if-else, and if-elif-else statements.
  • Write and debug code with conditionals.
  • Identify new syntactic elements related to the above.

0.4.0 A Simple Comparison

It is often useful to compare different variable values and execute different code based on those variables’ values.

  • For instance, checking if one variable is greater than another.
  • The mathematical expression for “x is greater than y” is \(x > y\)
  • In Python, it looks similar: x > y

Consider this program:

x = 5
y = 4

if x > y:
    print('X is larger than Y')

print("OK, we're done")

Exercise 0.4.1

Exercise 0.4.1

In ifexample.py, type up the above and examine the output. Then, change the value of y and see how the result differs. Submit with y = 6.

How does this work? First, observe:

conditional, explained

Now, at the moment the if statement executes, the condition is evaluated:

conditional, explained

If the condition is true then the code that’s indented below the if statement executes.

  • if statements use indented blocks to logically group code and execute it when conditions are met
  • For functions, the code executes when the function is called
  • For if statements, code executes when:
    • The program reaches the if statement, and
    • The condition after if is satisfied

Consider what happens when y is 6:

conditional, explained

Exercise 0.4.2

Exercise 0.4.2

Consider this program:

s = 0
for i in range(6):
    s = s + i

if s < 15:
    print('Less than 15')

print('Done')

Note: This statement evaluates a “less than” condition.

Try to mentally execute (trace its execution in your mind) and predict the output before typing it up in ifexample2.py to confirm.

A numeric variable can be: strictly less, less than or equal to, strictly greater, greater than or equal to, or equal to another numeric variable. Accordingly, the different types of less/greater comparisons are:

a < b      # Strictly less than, as when a=3, b=4
a <= b     # Could be less (a=3, b=5), could be equal (a=3, b=3) 
a > b      # Strictly greater (a=3, b=2)
a >= b     # Could be greater (a=3, b=1), could be equal (a=2, b=2)

We can also check for equality with == and inequality ==.

a == b # a and b are equal, such as a=3, b=3
a != b # a and are NOT equal: a=3, b is anything other than 3
 

Note that Python comparisons work between integers and floating point numbers, but equality requires that they are exactly equal. 10 is equal to 10.0 but not equal to 10.0000001 or 9.9999999.

if (1.5 + 1.5) == 3:
  print("1.5 plus 1.5 equals 3")
if (0.1 + 0.2) == 0.3:
  print("0.1 plus 0.2 equals 0.3")

What behavior do you expect from this program?

0.4.1 if and else

Think of else as if’s occasional partner.

Consider this example:

x = 5
y = 5

if x > y:
    print('X is larger than Y')
else:
    print('X is not larger than Y.')

print("OK, we're done")

Exercise 0.4.3

Exercise 0.4.3

Type up the above in ifexample3.py and examine the output. Then, change the value of x to 6. What is the output? Change y to 6. What is the output? Submit the code with x and y both set to 6.

When x is indeed larger than y, the code in the if body executes:

if/else, explained

When the if condition evaluates to false:

if/else, explained

What happens when x is 5 and y is 5?

if/else, explained

  • When x and y are equal, x is not greater than y, so the result of this conditional is the same as if x were less than y.
  • The conditional we wrote is only checking if x is greater than y, and the relationship between the two numbers does not otherwise matter.
  • If we want to check other conditions, like equality, we must explicitly write those checks into our code.

0.4.2  if-elif-else

Consider this variation:

x = 5
y = 5

if x > y:
    print('X is larger than Y')
elif y > x:
    print('X is not larger than Y?')
    print('Y is larger')
else:
    print('X and Y are equal')

print("Done")

Exercise 0.4.4

Exercise 0.4.4

Type up the above in ifexample4.py and examine the output. Then, try y=6 and y=4.

First, consider the case x=5, y=5:

if/elif/else, explained

Now consider x=5, y=4:

if/elif/else, explained

Next: x=5, y=6:

if/elif/else, explained

One can have as many elif sections as one would like, for example:

x = 3

if x == 1:
    print('one')
elif x == 2:
    print('two')
elif x == 3:
    print('three')
elif x == 4:
    print('four')
else:
    print('greater than four')

print('finished')

Think of the whole thing as a giant if statement: In the above case, when x is 3, the execution path through the giant if statement is:

many elifs

The execution pathway, illustrated:

many elifs

The execution pathway, described:

  • The if statement on Line 3 is false (x is not equal to 1), so its body on Line 4 is skipped
  • The elif statement on Line 5 is false (x is not equal to 2), so its body on Line 6 is skipped
  • The elif statement on Line 7 is true (x is equal to 3), so its body on Line 8 is executed
  • The remaining elif and else statements are skipped because one if or elif was True, and the program exits the conditional block and executes Line 14

Exercise 0.4.5

Exercise 0.4.5

Type up the above in ifexample5.py. Then, try each of x = 1, x = 2, x = 4, x = 5.

Consider this program:

x = 5
y = 4
z = 3

if x > y:
    print('X is larger than Y')

if x > z:
    print('X is larger than Z')
    print('X is the largest of the three')

Exercise 0.4.6

Exercise 0.4.6

Type up the above in ifexample6.py. Try y = 6. Explain why it does not logically work, even though the code runs. Then try to alter the program without changing the print statements so that it works in all cases for possible values of x, y, and z. That is, whichever of the above print statements gets printed correctly reflects the values of x, y and z.

End-Of-Module Problems

Full credit is 100 pts (complete at least two problems). There is no extra credit.

Starting with this module, we will sometimes give you starter code, including functions and tests. This is code to help set up the problem - you don’t have to understand the starter code, but you also shouldn’t change it.

Problem 0.4.1 (60 pts)

Problem 0.4.1 (60 pts)

Complete the function determine_polarity so that the function prints Positive if argument x is greater than 0, Negative if x is less than 0, and Zero if x is equal to 0.

def determine_polarity(x):
    # your code here

determine_polarity(5)
determine_polarity(-3.2)
determine_polarity(0)

The output should be:

Positive
Negative
Zero

Submit as polarity_check.py.

Problem 0.4.2 (60 pts)

Problem 0.4.2 (60 pts)

Complete the function check_winner such that You do not have the winning number. is printed if integer argument y is not 256, and You have the winning number! is printed if y is 256.

def check_winner(y):
    winning_number = 256

check_winner(25)
check_winner(255)
check_winner(256)

The output should be:

You do not have the winning number.
You do not have the winning number.
You have the winning number!

Submit as win_check.py.

Problem 0.4.3 (60 pts)

Problem 0.4.3 (60 pts)

Complete the function temperature report such that Today will be warm! prints if argument temperature is greater than 82, Today will be mild. prints if argument temperature is between 65 and 82 (inclusive), and Today will be cold! prints if argument temperature is less than 65.

def temperature_report(temperature):
    # your code goes here

temperature_report(83)
temperature_report(82)
temperature_report(72)
temperature_report(62)

The output should be:

Today will be warm!
Today will be mild.
Today will be mild.
Today will be cold!

Submit as temp_check.py.