Before you keep reading...
Runestone Academy can only continue if we get support from individuals like you. As a student you are well aware of the high cost of textbooks. Our mission is to provide great books to you for free, but we ask that you consider a $10 donation, more if you can or less if $10 is a burden.
Before you keep reading...
Making great stuff takes time and $$. If you appreciate the book you are reading now and want to keep quality materials free for other students please consider a donation to Runestone Academy. We ask that you consider a $10 donation, but if you can give more thats great, if $10 is too much for your budget we would be happy with whatever you can afford as a show of support.
16.9. Rainfall Problem
Let’s imagine that you have a list that contains amounts of rainfall for each day, collected by a meteorologist. Her rain gathering equipment occasionally makes a mistake and reports a negative amount for that day. We have to ignore those. We need to write a program to (a) calculate the total rainfall by adding up all the positive integers (and only the positive integers), (b) count the number of positive integers (we will count with “1.0” so that our average can have a decimal point), and (c) print out the average rainfall at the end. Only print the average if there was some rainfall, otherwise print “No rain”.
Construct a program that correctly solves the rainfall problem
# initialize the variables
rain = [0,5,1,0,-1,6,7,-2,0]
sumRain = 0
count = 0
---
# loop through the values in the list
for day in rain:
---
# if the value of day is positive
if day >= 0:
---
# add day to the sum
# also add one to count
sumRain = sumRain + day
count = count + 1.0
---
# if count is positive
if count > 0:
---
# calculate and print the average
ave = sumRain / count
print("Average",ave)
---
# otherwise
else:
---
# print no rain
print("No rain")
Type the program here and try it. Does it work like you thought it would?
Note
Discuss topics in this section with classmates.
You have attempted
of
activities on this page