Alex Kiss
Alex Kiss

Reputation: 11

Average Rainfall Calculator

This is the updated program I have written so far:

# This program averages rainfall per month.  It asks the user for the number
# of years.  It will then display the number of months, the total inches of
# rainfaill, and the average rainfall per month for the entire period.

# Get the number of years.

total_years = int(input('Enter the amount of years: '))

# Get the amount of rainfall for each month of each year.

for years in range(total_years):
    # Initialize the accumulator.
    total = 0.0
    print('Year', years + 1)
    print('----------------')
    for month in ('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'):
        inches = float(input(month))
        total += inches

total_inches = total

total_month = total_years * 12

average_inches = total / total_month



        # Display the average.
print('The total number of months is: ', total_month)
print('The total inches of rainfall is: ', total_inches)
print('The average rainfall per month for the entire period is: ', average_inches)

print()

This is the new error message I am getting when attempting to test the code:

Traceback (most recent call last):   File
"C:/Users/Alex/Desktop/Programming Concepts/Homework 2/Chapter
5/Average Rainfall maybe.py", line 23, in <module>
average_inches = total / month
TypeError: unspupported operand type(s) for /: 'float' and 'str'

Any ideas on how to fix/improve this code?

Now, all I need to fix is my calculations. I think they are wrong (lines 23-27).

Upvotes: 2

Views: 8896

Answers (1)

dbr
dbr

Reputation: 169573

The error messages references where the error occurred:

average_inches = total / month

Specifically,

TypeError: unspupported operand type(s) for /: 'float' and 'str'

..is saying it cannot divide a float (total) by a string (month).

month is the completely wrong thing to be dividing by (it's just a string containing "January" or whatever).. You want to divide by the number of months

As a hint, I'd suggest start by doing:

ALL_MONTHS = ('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'):

Then change your loop to:

for month in ALL_MONTHS:

That way you can refer to ALL_MONTHS again later...

Upvotes: 4

Related Questions