平均降雨量计算器

时间:2012-07-13 23:09:56

标签: python average

这是我到目前为止所写的更新程序:

# 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()

这是我在尝试测试代码时遇到的新错误消息:

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'

有关如何修复/改进此代码的任何想法?

现在,我需要解决的是我的计算。我认为他们错了(第23-27行)。

1 个答案:

答案 0 :(得分:4)

错误消息引用了错误发生的位置:

average_inches = total / month

具体地,

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

..说它不能用字符串(total)划分浮点数(month)。

month被分割是完全错误的(它只是一个包含“1月”或其他内容的字符串)..你想要除以number of months

作为提示,我建议先做:

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

然后将你的循环改为:

for month in ALL_MONTHS:

这样您可以稍后再次参考ALL_MONTHS ...