Conditionals#


Questions:#

  • How can programs do different things for different data?

Learning Objectives:#

  • Correctly write programs that use if and else statements and simple Boolean expressions

  • Trace the execution of conditionals


Use if statements to control whether or not a block of code is executed.#

  • An if statement (more properly called a conditional statement) controls whether some block of code is executed or not.

  • Structure is similar to a for statement:

    • First line opens with if and ends with a colon

    • Body containing one or more statements is indented (usually by 4 spaces)

In the next several cells, we’ll be considering the size (i.e., the diameter in km) of different planets.

size = 49357

if size > 10000:
    print('With a size of', size, ', this is a large planet')
With a size of 49357 , this is a large planet
size = 5937
if size > 10000:
     print('With a size of', size, ', this is a large planet')

Conditionals are often used inside loops.#

  • Not much point using a conditional when we know the value (as above).

  • But useful when we have a collection to process.

size = [5900, 36100, 33700, 7400, 10700]
for s in size:
    if s > 10000:
        print(s, 'is large')
36100 is large
33700 is large
10700 is large

Use else to execute a block of code when an if condition is not true.#

  • else can be used following an if.

  • Allows us to specify an alternative to execute when the if branch isn’t taken.

size = [5900, 36100, 33700, 7400, 10700]

for s in size:
    if s > 10000:
        print(s, 'is large')
    else:
        print(s, 'is small')
5900 is small
36100 is large
33700 is large
7400 is small
10700 is large

Use elif to specify additional tests.#

  • May want to provide several alternative choices, each with its own test.

  • Use elif (short for “else if”) and a condition to specify these.

  • Must come before the else (which is the “catch-all”)

size = [5900, 36100, 33700, 7400, 10700]

for s in size:
    if s > 30000:
        print(s, 'is very large')
    elif s > 10000:
        print(s, 'is large')
    else:
        print(s, 'is small')
5900 is small
36100 is very large
33700 is very large
7400 is small
10700 is large

Conditions are tested once, in order.#

Python steps through the branches of the conditional in order, testing each in turn — so ordering matters!

For example, here is a grading scheme no student would want used:

grade = 85

if grade >= 70:
    print('grade is C')
elif grade >= 80:
    print('grade is B')
elif grade >= 90:
    print('grade is A')
grade is C

We often use conditionals in a loop to modify the values of variables#

velocity = 5.0
for i in range(5): # execute the loop 5 times
    print('Step', i, ':', velocity)
    if velocity > 20.0:
        print('Moving too fast')
        velocity = velocity - 5.0
    elif velocity < 20.0:
        print('Moving too slow')
        velocity = velocity + 10.0
    else:
        print('Optimal speed')
Step 0 : 5.0
Moving too slow
Step 1 : 15.0
Moving too slow
Step 2 : 25.0
Moving too fast
Step 3 : 20.0
Optimal speed
Step 4 : 20.0
Optimal speed

To trace execution, we can create a table showing the values of i and velocity each time through the loop:

i

velocity

-

5

0

5

1

15

2

25

3

20

4

20

Compound Relations Using and & or#

Often, you want to check if some combination of things is true. You can combine relations within a conditional using and and or. Here’s an example with the size of the planet and its corresponding biodiversity. In this example, pop is short for the population of all living creatures found on the planet (our imaginary space travelers have very advanced measurement devices for counting such things!). Let’s define an “interest” index for planets whereby a planet is considered “Very interesting” if it is large (size > 10,000) and biodiverse (pop > 10 m); “interesting” if it is large or biodiverse (but not both); ‘or “not interesting” if it is neither large nor biodiverse (for some reason, our explorers are biased towards big planets populated by many living creatures).

size = [5900, 36100, 33700, 7400, 10700, 27538, 36180, 6557]
pop = [3.6,    8.2,  10.4,  4.6,   10.1,  10.7,   0.3,  0.7]

for i in range(8):
    if pop[i] > 10.0 and size[i] > 10000:
        print('planet is very interesting')
    elif pop[i] > 10.0 or size[i] > 10000:
        print('planet is interesting')
    else:
        print('planet is not interesting')
        
planet is not interesting
planet is interesting
planet is very interesting
planet is not interesting
planet is very interesting
planet is very interesting
planet is interesting
planet is not interesting

Sometimes you may want to combine multiple and/or statements. For example, continuing the example above, we could define further nuance whereby a planet could be considered “very interesting” if has a population > 10 m and it is larger than > 10,000 or if it has a size > 30,000 regardless of its population size. We could re-write the first conditional statement from the above example as:

if pop[i] > 10.0 and size[i] > 10000 or size[i] > 30000:
    print('planet is very interesting')

However, this is potentially ambiguous — it could mean either:

  • if population is > 10 and the size is either > 10,000 or > 30,000

  • i.e., if pop[i] > 10.0 and (size[i] > 10000 or size[i] > 30000)

or

  • if the population is > 10 and the size is > 10,000, or, if the size is > 30,000

  • i.e., (if pop[i] > 10.0 and size[i] > 10000) or size[i] > 30000

Of the above two examples, only the second meets our new definition of “very interesting”. The first example will fail because it only tests if size > 30,000 if population is > 10.

Python has a precedence order (“order of operations”) whereby it evaluates and before or. However, just like with arithmetic, you can and should use parentheses (as in the code examples above)whenever there is possible ambiguity. A good general rule is to always use parentheses when mixing and and or in the same condition.


Exercises#

Compound relations#

Try each of the above three examples of combining and and or operators and see how the results differ (or not).

for i in range(8):
    if pop[i] > 10.0 and size[i] > 10000 or size[i] > 30000:
        print('planet is very interesting')
    elif pop[i] > 10.0 or size[i] > 10000:
        print('planet is interesting')
    else:
        print('planet is not interesting')
planet is not interesting
planet is very interesting
planet is very interesting
planet is not interesting
planet is very interesting
planet is very interesting
planet is very interesting
planet is not interesting

Tracing Execution#

Without executing the code, predict what this program prints. You can then run it to see if your answer is correct.

pressure = 71.9
    
if pressure > 50.0:
     pressure = 25.0
elif pressure <= 50.0:
     pressure = 0.0
        
print(pressure)

Trimming Values#

Fill in the blanks so that this program creates a new list containing zeroes where the original list’s values were negative, and ones where the original list’s values were positive.

original = [-1.5, 0.2, 0.4, 0.0, -1.3, 0.4]
result = ____
for value in original:
    if ____:
        result.append(0)
    else:
        ____
            
print(result)

Initializing#

Modify this program so that it finds the largest and smallest values in the list no matter what the range of values originally is.

values = [-2, 1, 65, 78, -54, -24, 100]

# Initialize accumulator variables as numeric with no value
smallest = None
largest = None

for v in values:
    # test if accumulator variables have a value or are None
    if ____:
        smallest = v
        largest = v
    # If accumulators are not none, test if they should be updated with current value of v
    ____:
        smallest = min(____, v)
        largest = max(____, v)
        
print(smallest, largest)

Follow-Up Questions#

  • What would be a simpler way of finding the smallest and largest values in the list values?

  • What are the advantages and disadvantages of using the method above to find the range of the data?

Identifying Variable Name Errors#

  1. Read the code below and try to identify what the errors are without running it

  2. Run the code and read the error message

    • What type of NameError do you think this is?

    • Is it a string with no quotes, a misspelled variable, or a variable that should have been defined but was not?

  3. Fix the error

  4. Repeat steps 2 and 3, until you have fixed all the errors

for number in range(10):
    # use a if the number is a multiple of 3, otherwise use b
    if (Number % 3) == 0:
        message = message + a
    else:
        message = message + "b"
        
print(message)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[10], line 3
      1 for number in range(10):
      2     # use a if the number is a multiple of 3, otherwise use b
----> 3     if (Number % 3) == 0:
      4         message = message + a
      5     else:

NameError: name 'Number' is not defined

Summary of Key Points:#

  • Use if statements to control whether or not a block of code is executed.

  • Conditionals are often used inside loops.

  • Use else to execute a block of code when an if condition is not true.

  • Use elif to specify additional tests.

  • Conditions are tested once, in order.


This section was adapted from Aaron J. Newman’s Data Science for Psychology and Neuroscience - in Python and Software Carpentry’s Plotting and Programming in Python workshop.