15.8. Rainfall Problem

Let’s imagine that you have a list that contains amounts of rainfall for each day, collected by a meteorologist. We want to figure out the average rainfall from the list. However, her rain gathering equipment occasionally makes a mistake and reports a negative amount for that day. We have to ignore those.

We will build the program gradually in the following steps:

15.8.1. Rainfall Step 1

First, lets not worry about filtering out the bad values or finding the average. Let’s just calculate the total of the values in the list.

We will write the code in a function getRealAvg so that it is easier to test with different possible lists of data - we will get a different list for each month of data, so we need our program to work correctly for any list it is given. This function should add all of the values in rainList to the variable sumRain which will be the answer it returns.

Right now that name is not accurate because we are not calculating the average yet, but it will be an appropriate name when we complete the program.

While working on the program, you may want to use codelens or print out information so you can see what is happening as the code runs. You can also comment out one of the two tests to focus on the other one.

15.8.2. Rainfall Step 2

Now, let’s worry about about ONLY adding the values of the numbers that aren’t negative to the total. You can copy your code from part 1 and use it to get started here. Then add logic so that you only add each value to sumRain if it is 0 or more.

Hint: The if condition needs to be checked for each value in the list. You must nest the if inside the for.

Again, use codelens or print statements to understand what your code is doing. You may want to print each value that you add to the list so you can see if the right ones are being included.

15.8.3. Rainfall Step 3

To get the average, we need to know how many values we have added up. If we were using all of the values, we could simply do len(rainList). But since we only are going to use some of the values, we need to calculate how many there are.

We will make a variable count and use that to keep track of the number of items. Add the code you have written so far to the program below. Then add code so that each time you add a value to sumRain, you add 1 to count.

For now, we will just return the count so we can see if this new code is working correctly. Leave the code for sumRain there, once we are sure the count is correct we will use both values to get the average.

Again, use codelens or print statements to understand what your code is doing.

15.8.4. Rainfall Finished

Now that we know we have the right sum and count, you can finish the function by returning the average from the function. Use the code you have already written, but write new code to calculate and return the average.

You have attempted of activities on this page