Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Day 05: In-class Assignment

University of Missouri

✅ Put your name here.

✅ Put your group member names here.

Plant cover classes and saguaro mortality

People in wash with setting sun, saguaros, and lens flare

Credits: National Park Service

Learning goals for today’s assignment

  • Review code that uses if, elif, and else statments and understand the logical flow of the program

  • Write if/elif/else statements in Python.

  • Create and use basic functions in Python.

Assignment instructions

Work with your group to complete this assignment. Instructions for submitting this assignment are at the end of the Notebook. The assignment is due at the end of class.


Background

As mentioned in the pre-Class, the survival probability for saguaros is not just a matter of age but also of cover plants around it.

Kaplan-Meier survival probability curves for saguaros that were established during the episode of regeneration between 1959 and 1993.

Credits: Orum et al (2016)

✅  Question:

  • What can you infer from Figure 8 from the original paper?

  • What saguaros have be the best survival odds as they age? What saguaros are worst off?

Put your answer here


1. Understanding if statements in Python

As you saw in the pre-class assignment, if statements provide an mechanism for “branching” to occur in your code. Depending on whether or not something is determined to be true, your code can pursue one branch, or another, or do nothing at all. The else statement allows your code to execute something even if none of the if or elif statements you write are found to be true. By combining these sorts of commands in a variety of ways we can create a very complex system of branches in our code.

✅  As a group, review and run the following bit of example code.

✅  As a group, add comments to explain what various parts of the code are doing.

cover_plants = ['Condalia warnockii', 'Parkinsonia microphylla', 'Parkinsonia microphylla /Acacia(Senegalia) greggii',
                'Parkinsonia microphylla /Prosopis velutina', 'Prosopis velutina', 'Prosopis velutina/Parkinsonia microphylla']
paloverdes = 0
for i in range(len(cover_plants)):
    if 'Parkinsonia microphylla' in cover_plants[i]:
        print(cover_plants[i], ' --> Cover includes paloverde')
        paloverdes += 1
    else:
        print(cover_plants[i], ' --> No paloverde registered')

print('\nA total of', paloverdes,'paloverdes were registered\n====\n')
for cover in cover_plants:
    if 'Parkinsonia microphylla' == cover:
        print(cover, ' --> Cover is exclusively paloverde')
    elif 'Parkinsonia microphylla' in cover:
        print(cover, ' --> Cover includes paloverde')
    else:
        print(cover, ' --> Cover has no paloverde')
Condalia warnockii  --> No paloverde registered
Parkinsonia microphylla  --> Cover includes paloverde
Parkinsonia microphylla /Acacia(Senegalia) greggii  --> Cover includes paloverde
Parkinsonia microphylla /Prosopis velutina  --> Cover includes paloverde
Prosopis velutina  --> No paloverde registered
Prosopis velutina/Parkinsonia microphylla  --> Cover includes paloverde

A total of 4 paloverdes were registered
====

Condalia warnockii  --> Cover has no paloverde
Parkinsonia microphylla  --> Cover is exclusively paloverde
Parkinsonia microphylla /Acacia(Senegalia) greggii  --> Cover includes paloverde
Parkinsonia microphylla /Prosopis velutina  --> Cover includes paloverde
Prosopis velutina  --> Cover has no paloverde
Prosopis velutina/Parkinsonia microphylla  --> Cover includes paloverde

✅  Question 1

What is the difference between in and ==?

Write your response here

✅  Question 2

What does the len() function do?

Write your response here

✅  Question 3

What does the range() function do?

Write your response here

✅  Question 4

What does to the paloverde variable register? What does += 1 do?

Write your response here


2. Writing your own if statements

Sometimes in computational modeling and data science, you need to be able parse data and execute particular tasks based on the how data points compare to each other. Conditional statements that use things like <, >, >=, or == combined with logical operators like and and or provide an excellent mechanism for comparing values! Try the following:

✅  Task 5

Write code that compares three variables v1, v2, and v3 (initial values are provide below) and does the following using if statements:

  1. If v1 is equal to v2, print “woohoo!”

  2. If v1 is the smallest value of the three (i.e., v1 is less than both v2 and v3), print out “v1 is tiny!”

  3. If v1 is the smallest value of the three, add a nested if statement to print out a statement saying whether v2 or v3 is the largest value.

Try several values of v1, v2 and v3 and ensure that you see the correct behavior.

Suggestion: Make sure you work together with your group to solve this. Planning it out on the whiteboard can also be useful!

Note: Although you learned briefly about functions in your pre-class assignment, don’t worry about using functions just yet!

# Put your code here. Initial values for v1, v2, and v3 are provided.
# Make sure to test out new values to ensure your code works as intended!

v1 = 1
v2 = 4
v3 = 3

✅  Question 6

What happens in your code if either v2 or v3 is less than v1? If you’re not sure, test it out with a bit of code (learning by breaking is very useful!)

Put your answer here


3. Counting saguaros for each cover class

3.1 Loading more data and counting with ifs

Make sure you download the census_saguaro_cover_classes.csv file (available in Canvas) and place it in the same directory for this Notebook. By running the cell below we get two lists:

  • coverplants: The scientific name/s of the cover plants found around each saguro

  • coverclass: Each saguaro’s cover class

One list entry per saguaro. The elements in each list correspodn to each other. E.g. for the 0-th indexed saguaro, we know it was covered by coverplants[0] = 'Acacia (Vachellia) constricta' (whitethorn acacia), which means this saguaro is part of the coverclass[0] = 'C2' cover class.

# Just run this cell

import pandas as pd
df = pd.read_csv('census_saguaro_cover_classes.csv', index_col=0)
coverplants, coverclass = [ df[key].tolist() for key in ['NURSE PLANT', 'COVER CLASS']]
print(coverplants[:5])
print(coverclass[:5])
['Acacia (Vachellia) constricta', 'Parkinsonia microphylla', 'Parkinsonia microphylla', 'Parkinsonia microphylla', 'Ephedra sp.']
['C2', 'C1', 'C1', 'C1', 'C2']

✅  Task 8

  • Write a for loop that loops around all the cover plants

  • Count the number of saguaros for which mesquite (Prosopis velutina) is present.

    • Keep in mind that for some saguaros, mesquite is just one of the plants present, not the only one.

  • Print the scientific name of mesquite and the number you just counted

  • Does it match the number listed in Table 1 from Orum et al.?

Hint: Look at the code from Part 1

# Your code here

✅  Task 9

Now repeat the code to count the number of saguaros for which Mexican crucillo (Condalia warnockii) is present. Does it match Table 1?

# Your code here

3.2 Counting functions

You probably noticed that the code from Tasks 8 and 9 is pretty much the same. The saguaro survey reported 21+ different cover plants. Repeating the code above 21 times, while not outlandish, it will not be fun. Let’s make a counting function instead.

We can make a function to count the number of times a plant name shows up in the coverplants list. But functions work best when they are as general as possible. Why limit the function to plant names?

✅  Task 10

  • Define a function times_in_list that takes two inputs:

    • A name (a string variable)

    • A list (containing string variables). Remember that you cannot use list as a variable name.

  • The function must return one numerical value

    • The number of times the given name was found in the list

# Define your function

✅  Task 11

Test your function! Use your function to count the number of saguaros covered by paloverdes (Parkinsonia microphylla). It should be 402 (not 403 as listed in Table 1).

# Test your function

3.3 Bring it all together: counting for all the plants within the same class

We now have a quick way to count the number of times a specific plant is present in the coverplants list. But a cover class comprises several plants. Below are three lists, one per class, listing the scientific names of the cover plants found in each cover class.

✅  Task 12

  • Write a loop that loops through all the Class 2 cover plants

  • For each of these plants, print the (scientific) name of the plant next to the number of saguaros with this plant around

For some reason, the numbers do not fully match Table 1 (but they are in the same ballpark). The final count numbers should be:

Acacia (Vachellia) constricta   64
Larrea tridentata               46
Acacia (Senegalia) greggii      20
Ephedra sp.                     12
# Count the number of saguaros for all the C1 saguaros

c1_plants = ['Parkinsonia microphylla', 'Prosopis velutina', 'Condalia warnockii']
c2_plants = ['Acacia (Vachellia) constricta','Larrea tridentata','Acacia (Senegalia) greggii','Ephedra sp.']
c3_plants = ['Isocoma tenuisecta','Zinnia acerosa','Psilostrophe Cooperi','grass','open']

3.4 But what about Other species?

So far our code works whenever we want to count a specific plant or set of plants. But what about counting every other species that was not part of the initial c2_plants list? Table 1 reports 13 saguaros covered by Other species for C2.

✅  Question 13

  • Without coding anything, discuss with your peers how would you count the number of C2 saguaros that are covered by “Other plant species”

  • What parts of your strategy seem like a copy/paste matter?

  • What parts of your strategy would require more coding/functions?

Put your answer here


🛑 STOP

Check in with an instructor before you read further

The rest of today’s assignment is time-permitting


One possible strategy to deal with Other species is as follows:
  1. First count the number of saguaros in the C2 class.

  2. Then count the number of saguaros with explicitly defined cover: simply add the numbers from Task 12

  3. The difference between these two steps should be Other species

(For the next in-class we will explore a different strategy)

✅  Task 14

  • Write some code to perform step (1)

  • Notice that you actually only need one line: you already have a function to the counting for you!

There should be 150 class C2 saguaros

# Count the number of saguaros in the C2 class

✅  Task 14 (continued):

  • Now manually (i.e. without coding any extra functions), add the numbers as in step (2) and print the result

  • Then manually find the difference as in step (3) and print the result

Remember that you can use Python as a calculator.

# Use Python as a calculator and then print the results

✅  Question 15

  • Does the printed result match the Table 1 for “Other species”?

  • What do you think went wrong in the strategy?

Put your answer here

3.4 A new function and counting strategy

In step (2), if we add the numbers from Task 12 we are double-counting some saguaros! For example, one saguaro has a Larrea tridentata/Acacia (Vachellia) constricta cover, i.e., it is covered both by a whitehorn acacia and a creosote bush. This one saguaro is counted as two in Task 12! (For Task 12 purposes that’s fine, though).

We need a way to count the number of saguaros covered by at least one of the specified cover plants. And count it only once.

✅  Task 16

  • Read and comment the following code below. What does each function do?

# Add comments to the following new functions
# What is different between `times_in_list`
# What does `break` do?

def times_in_list_unique(list_of_names, my_list):
    counter = 0
    for item in my_list:
        for name in list_of_names:
            if name in item:
                counter += 1
                break # Check: https://docs.python.org/3/reference/simple_stmts.html#break

    return counter

✅  Task 16 (continued):

  • Read and comment the following code below. Does the “other species” counter now match Table 1? (The actual count should be 12, not 13)

# Add comments to the following code
# Then run it for the C3 class of cover plants
c = 'C2'
class_count = times_in_list( c , coverclass)
print('===', c, ':', class_count, 'total ===')

for plant in c2_plants:
    plant_count = times_in_list(plant, coverplants)
    print(plant, plant_count, sep='\t')
other = class_count - times_in_list_unique(c2_plants, coverplants)
print('Other species', other, sep='\t')
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[12], line 4
      1 # Add comments to the following code
      2 # Then run it for the C3 class of cover plants
      3 c = 'C2'
----> 4 class_count = times_in_list( c , coverclass)
      5 print('===', c, ':', class_count, 'total ===')
      7 for plant in c2_plants:

NameError: name 'times_in_list' is not defined

Congratulations, you’re done!

Submit this assignment by uploading it to the course Canvas web page. Go to the “In-class assignments” folder, find the appropriate submission link, and upload it there.

See you next class!

© Copyright 2026, Division of Plant Science & Technology—University of Missouri

References
  1. Orum, T. V., Ferguson, N., & Mihail, J. D. (2016). Saguaro (Carnegiea gigantea) Mortality and Population Regeneration in the Cactus Forest of Saguaro National Park: Seventy-Five Years and Counting. PLOS ONE, 11(8), e0160899. 10.1371/journal.pone.0160899