Homework 2: Dictionaries, If Statements, Functions, and Modules#

✅ Put your name here

#

CMSE 201 – Spring 2025#

CMSE Logo

Learning Goals#

Content Goals#

  • Use if/elif/else statements to implement a logical flow

  • Write and execute functions

  • Use the numpy module for math and data

  • Display data on plots using matplotlib

  • Utilize dictionaries to store data

Practice Goals#

  • Coding conventions

  • More advanced debugging

  • Using functions to build reusable/transferable code

  • Use visualization best practices to make informative plots

Rubric#

Academic Integrity - 2 points

  1. Dictionaries (10 points total)

  2. Debugging Functions (10 points total)

  3. Functions, if/else, and Exoplanets (15 points)

  4. Numpy, matplotlib, and functions (23 points)

Total points possible: 60

Assignment instructions#

Work through the following assignment, making sure to follow all the directions and answer all the questions.

This assignment is due at 11:59 pm on Friday, October 3rd. It should be uploaded into the “Homework Assignments” submission folder for Homework #2. Submission instructions can be found at the end of the notebook.

Academic integrity statement (2 Points)#

In the markdown cell below, paste your personal academic integrity statement. By including this statement, you are confirming that you are submitting this as your own work and not that of someone else.

Put your personal academic integrity statement here.


1. Dictionaries (10 Points)#

Python dictionaries are particularly useful for keeping track of pieces of information of different types.

Dictionaries are made up of keys and values. I like to think of keys as physical keys and values as the treasures (information) that I obtain by using the keys. Each key works to unlock a different treasure. For example, I might have a key that is “Bald eagle” and the value associated with that key could be the primary color of the bald eagle “Brown”. To continue the example, I could have another key that is “Swan” and the value associated with this key would be “White”. We now have two keys that are birds and two values associated to each key that are the birds primary colors. We now have a dictionary! We could call this dictionary “Bird_Colors”.

Let’s code up this example dictionary to see what it looks like in python.

Bird_Colors = {"Bald eagle" : "Brown",
               "Swan" : "White"}

✅  1.0 Task (1 Point)#

Using your preferred search engine or AI tool, research information on basics of dictionaries. Try and specifically learn information about dictionary basics that are confusing to you. Write down either an example you found or something you learned about dictionaries below. Make sure you also cite your source used.

#Write your answer here

✅  1.1 Task (2 Points)#

Now it’s your turn. We have given you two birds, now add ten more entries to this dictionary (for a total of twelve entries). Remember that your keys should be birds, and the values should be each birds primary color. Try and find some interesting birds! Be creative!

# Put your answer here

✅  1.2 Task (2 Points)#

Now that you have a dictionary, we should practice using it! We want to use our keys in order to access the values that have information. Start by researching “How to access values from keys in python dictionaries” and recording what you find. Use whatever resource you like best to find information, but make sure you properly cite your source and use.

# put your answer here on how to access values from key

✅  1.3 Task (1 Point)#

Now, take what you have learned in part 1.2 and apply it here. Display the values from three different keys in your Bird_Colors dictionary.

# put your answer here

✅  1.4 Task (2 Points)#

Now I’d like you to flip your dictionary. Create a new dictionary where all of your values (the colors) are now keys, and all of your keys (the birds) are now values. If you have one color that corresponds to many different birds, you should write your dictionary in a way that accounts for this.

If all of your birds had unique colors, add one more bird with the same color.

# put your answer here

✅  1.5 Task (2 Points)#

Lastly, Using dictionary keys, write a loop that will print out the number of birds there are for each color. Display the name of the color and next to it the number of birds. For example I might have:

Brown : 2
White : 1
Grey : 7
Blue : 2

If you are having trouble starting this question, break it down into parts:

  1. Loop through the keys (colors) in your dictionary

  2. Initialize a counter variable to keep track of how many values (birds) there are per key (color)

  3. Loop through each value (bird) attached to each key (color) in your dictionary and add to your counter.

  4. Print out the color and the counter variable before restarting your loop and resetting your counter variable back to zero.

# put your answer here

2. Debugging a Function (10 Points)#

In the Tasks below, you will be asked to find, describe, and fix the bugs in each example.

✅  2.1 Task (5 Points )#

In the cell below, you will find a function that should take in a list of 5 grades between 0 and 100 and returns the corresponding total grade, based on the respective grade weight we use for CMSE 201. However, when we test our function, we are getting an error.

In total there happens to be four different ‘bugs’ messing up our code. Note that bugs can be either “python language” bugs, “mathematical model” bugs, or often some combination of the two.

✅  In the cell beneath where we test the function, do the following:

  1. State where each bug is occurring,

  2. Fix the bug in the function, and

  3. In the text box provided, indicate how you checked to see that the function works correctly after you have fixed it.

Note: When attempting this question, we recommend fixing the code one bug at a time. Start by running the two code cells and debugging the first error message that comes up. Then when you think you have corrected the bug, check (by running your code cells) to see if the same error persists. If you see that a new error is occuring on a different line, that might be an indication that you fixed the previous bug and are now encountering the new bug. Repeat this process till you have no error messages, and the function output makes sense.

def calculate_total_grade(grades):
    """
    Calculate the total grade based on weighted components.
    
    Parameters:
    grades (list): A list of 5 numeric grades (0–100) in the following order:
                   [Participation, Pre-class, Quizzes, Homework, Projects]
    
    Returns:
    float: The total weighted grade.
    """
    if grades != 5:
        print("Too many or not enough values in your grade list, You must provide exactly 5 values.")
    
    weights = [0.15, 0.15, 0.20, 0.25, 0.25]
    for i in len(range(grades)):
        total = weights[i]*grades[i]
    
    return total
test_data = [90, 85, 88, 92, 95]
final_grade = calculate_total_grade(grades)
print(final_grade)

# Document the first bug here!

# Document the second bug here!

# Document the third bug here!

# Document the fourth bug here!

Put your answer to how you know the function is working as intended after fixing all the bugs here

✅  2.2 Task (5 Points)#

In the cell below, there are 5 common python errors that occur. For each error, write what the error is, comment out the lines with the error, and then in a new line, fix the error.

We ask that you comment out the error rather than actively modify it so that you can always come back to this homework and see various error messages by uncommenting the bugged code.

# 1. What is the error?
print("my string is this)
# Write the fixed code here

# 2. What is the error?
print(this_variable)
# Write the fixed code here

# 3. What is the error?
result = "string" + 5
# Write the fixed code here

# 4. What is the error?
number = int("five")
# Write the fixed code here

# 5. What is the error?
my_list = [1, 2, 3]
print(my_list[3])
# Write the fixed code here

3. Functions, If/Else, and Stars! (15 Points)#

Astronomers classify stars into categories based on their surface temperature (in Kelvin). Two important ranges are:

  • Sun-like (G-type): 5,300-6,000 K

  • Hot stars (O/B-type): 10,000-50,000 K

3.1 Writing a Boolean Function (3 points)#

Choose whether you want to check for Sun-like stars or Hot stars in a dataset. Write a function that takes in a star’s temperature (in Kelvin) and returns True if the star falls within the chosen range and False otherwise. Demonstrate your function on a test dataset.

# Example test data
stellar_temp_test_data = [4000, 5500, 5800, 12000, 30000, 7000]

3.2. Extending to the Full Data Set (2 points)#

In the cell below, you will find a data set of planetary temperature (in units of Kelvin as above). Use your function on the dataset of stellar temperatures to count how many stars fall into the chosen category.

stellar_temps = [4000, 5500, 5800, 12000, 30000, 7000, 5200, 15000, 6500,7890, 23000, 5600, 5500,59000]

3.3. Adding Complexity (3 points)#

What if you wanted to categorize stars into more than two categories?? In the cell below, write a new function that takes in a stellar temperature (in Kelvin) and categorizes the star as Sun-like, Hot star, or Other.You can choose to build from your previous code or start from scratch. Use your dataset to determine the number of Sun-like and Hot stars.

# put your work here

3.4 Documenting Your Solution Pathway (5 points)#

Answer the following questions in detail:

  1. Indicate which portions of section 3 of this homework you answered with prior knowledge, and also indicate which portions you answered with the help of outside sources (e.g. generative AI, past assignments, Stack Overflow, Google, etc.) to help you? (1/2 point)

  2. For the parts were you DID use external resources, document what sources you used and how they informed your approach. If you used generative AI, be sure to include prompts and outputs. For the parts where you DID NOT use external resources, what prior knowledge did you recall to solve the problem? (2 points)

  3. Does your solution work? (1/2 point)

  4. If your solution works, how do you know it works? Include any calculations you made, tests you ran, etc. If your solution DOES NOT work, how do you know it does not work? What approaches would you use to verify a correct solution? (2 points)

Put your answer here.

3.5 Reflections (2 points)#

✅  In the cell below, answer the following reflection questions:

  • In Part 3.3, did you use your function from 3.1 at all?

  • In what way? (Or if you didn’t, why not?)

  • Is writing a function the most efficient way to solve the problem? Why or why not? What other ways could you solve it?

Put your answers here.

4. Numpy, matplotlib, and functions (18 Points)#

4.1 Making a plotting function (6 points)#

In CMSE 201, you will be making plots often. To help future you save time, you are going to write a function to use when you make plots!

✅  In cells below, write a function that takes in arrays of x and y values and displays a plot containing 4 subplots. Use plt.subplot() and include labels, line shapes, and colors to make the plots clear.

For this exercise, you will analyze monthly average CO\(_2\) concentrations (in parts per million, ppm) from four different monitoring stations. The data represent deviations relative to a 1958 baseline. For example, in 1960, Mauna Loa measured 318 ppm, while by 2020, it had climbed above 410 ppm.

Hint: Rather than hard-coding axis labels and legend labels, consider passing them in as function arguments. This makes your function reusable for other datasets.

You must also test your function with the test data to receive full credit

# test data here
import numpy as np

years = np.array([1960, 1970, 1980, 1990, 2000, 2010, 2020])
mauna_loa = np.array([318, 325, 338, 354, 369, 390, 414])
barrow = np.array([316, 323, 335, 351, 367, 388, 412])
cape_grim = np.array([315, 322, 334, 349, 365, 386, 410])
south_pole = np.array([314, 321, 333, 347, 364, 385, 409])
# put your answer here

✅  Reflection question: In the cell below, use 2–3 sentences to explain why using arguments for labels is preferable to hard-coding them.

Put your answers here.

4.2 Using numpy arrays and functions for calculations (6 points)#

Absolute values tell us levels, but percent change reveals how quickly each site’s CO\(_2\) concentration is increasing.

We can calculate the percent change as follows:

\(\% \ change = \frac{(final-initial)}{initial} \times 100\)

✅  In the cell below, write a function that takes in an array of CO\(_2\) values and calculates the percent change between each consecutive value. Demonstrate that your function works with one of the arrays above.

# put your code here

4.3 Putting it all together (6 points)#

Along with this homework assignment, a CSV file is provided with atmospheric CO\(_2\) concentration data from the same four stations.

✅  In the cell(s) below, use the data from the file (and the functions you wrote) to calculate the percent difference and generate plots for plots for the regions in the CSV data file.

NOTE: This homework only includes up to Day 9 content which does not include the pandas module. Therefore, you should use the numpy module for this problem. It is designed to be simpler with numpy!

Remember that you can open up data files in Jupyter to see what the data looks like!

# put your work here

4.4 Documenting Your Solution Pathway (5 points)#

Answer the following questions in detail:

  1. Indicate which portions of section 4 of this homework you answered with prior knowledge, and also indicate which portions you answered with the help of outside sources (e.g. generative AI, past assignments, Stack Overflow, Google, etc.) to help you? (1/2 point)

  2. For the parts were you DID use external resources, document what sources you used and how they informed your approach. If you used generative AI, be sure to include prompts and outputs. For the parts where you DID NOT use external resources, what prior knowledge did you recall to solve the problem? (2 points)

  3. Does your solution work? (1/2 point)

  4. If your solution works, how do you know it works? Include any calculations you made, tests you ran, etc. If your solution DOES NOT work, how do you know it does not work? What approaches would you use to verify a correct solution? (2 points)

Put your answer here.


Congratulations, you’re done!#

Submit this assignment by uploading it to the course Desire2Learn web page. Go to the “Homework Assignments” section, find the submission folder link for Homework #2, and upload it there.