4 Use Python Based on chapter 7 Arrays Use Python for the f
4. Use Python: Based on chapter 7 - Arrays. Use Python for the following problem.
a) Allow the user to enter the number of months for which we want to record rainfall. The number of months would be an input supplied by the user. For example, if we want to record rainfall for 5 months, the user will enter 5 for this input. Validate this entry, so only numbers between 1 and 12 are allowed.
b) Read the rainfall amount for each month into an array. You will need a loop here.
c) Calculate and display the grand total of the rainfall amounts for the given months.
d) Calculate and display the average rainfall for the given months.
e) Find and display the month with the highest rainfall. DO NOT use any predefined Python functions
. f) Find and display the month with the lowest rainfall. DO NOT use any pre-defined Python functions.
g) Display the amount of rainfall for each month. Make sure the output is descriptive.
The following is an example for a test run. If the user has data for 3 months, she will enter 3 for the number of months. The user will then be prompted for the amount of rainfall. Let’s say the user enters 2 for the first month, 5 for the second month and 4 for the third month. The program will calculate the grand total amount of rainfall as 11. The average will be 3.66 (note: 11/3 = 3.66 – Format the output numbers to 2 digits after the decimal pint). The program also calculates month 2 as the month with the highest rainfall and month 1 as having the lowest rainfall.
Solution
Here is the code for you:
#!/usr/bin/python
#Allow the user to enter the number of months for which we want to record rainfall.
numOfMonths = input(\'Enter the number of months: \')
#Validate this entry, so only numbers between 1 and 12 are allowed.
while numOfMonths < 1 or numOfMonths > 12:
print \'The number of months should be in the range 1 - 12. Try again.\'
numOfMonths = input(\'Enter the number of months: \')
#Read the rainfall amount for each month into an array. You will need a loop here.
rainFalls = []
for i in range(numOfMonths):
rainFalls.append(0.0)
print \'Enter the rainfall for month #: \', (i+1),
rainFalls[i] = input()
# Calculate and display the grand total of the rainfall amounts for the given months.
#Find and display the month with the highest rainfall.
#Find and display the month with the lowest rainfall.
totalRainfall = 0.0
maxRainfall = 0
minRainfall = 0
for i in range(numOfMonths):
totalRainfall = totalRainfall + rainFalls[i]
if rainFalls[i] > rainFalls[maxRainfall]:
maxRainfall = i
if rainFalls[i] < rainFalls[minRainfall]:
minRainfall = i
avgRainfall = totalRainfall / numOfMonths
print \'Total rainfall is: \', \'%.2f\' %totalRainfall
print \'Average rainfall is: \', \'%.2f\' %avgRainfall
print \'Month \', (maxRainfall+1), \' has the highest rainfall.\'
print \'Month \', (minRainfall+1), \' has the lowest rainfall.\'
